Last active
August 29, 2015 14:22
-
-
Save beoliver/98968a2ec1f1fb8a54f7 to your computer and use it in GitHub Desktop.
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 Memoize(object): | |
def __init__(self, f): | |
self.f = f | |
self.computed = {} | |
def __call__(self, *args): | |
xs = self.computed.get(args) | |
if xs : | |
return xs | |
else : | |
value = self.f(*args) | |
self.computed[args] = value | |
return value | |
def unmemoize(self): | |
return self.f | |
def fact(n): | |
print("computing", n) | |
if n == 0: | |
return 1 | |
else: | |
return fact(n-1) * n | |
fact = Memoize(fact) | |
# fact(5) | |
# fact(6) | |
# ... | |
fact = fact.unmemoize() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment