Skip to content

Instantly share code, notes, and snippets.

@ptigas
Created March 6, 2012 20:17
Show Gist options
  • Save ptigas/1988734 to your computer and use it in GitHub Desktop.
Save ptigas/1988734 to your computer and use it in GitHub Desktop.
memento decorator applied on fibonacci
class Memento :
__mem__ = {}
def __init__(self, f) :
self.f = f
def __call__(self, arg) :
if arg not in self.__mem__ :
self.__mem__[arg] = self.f(arg)
return self.__mem__[arg]
def fib1( n ) :
if n <= 1 :
return 1
return fib1(n-1) + fib1(n-2)
@Memento
def fib2( n ) :
if n <= 1 :
return 1
return fib2(n-1) + fib2(n-2)
print 'Computing fib without memento ....', fib1(35)
print 'Computing fib wth memento ....', fib2(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment