Created
March 6, 2012 20:17
-
-
Save ptigas/1988734 to your computer and use it in GitHub Desktop.
memento decorator applied on fibonacci
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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