Last active
December 21, 2015 18:48
-
-
Save reillyeon/6349482 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
import functools | |
def compute_once(f): | |
class ComputeOnce(object): | |
def __call__(self): | |
value = f() | |
self.__class__.__call__ = lambda x: value | |
return value | |
return ComputeOnce() | |
def memoize(f): | |
d = {} | |
@functools.wraps(f) | |
def compute(*args, **kwargs): | |
key = (args, tuple(kwargs.items())) | |
try: | |
return d[key] | |
except KeyError: | |
value = f(*args, **kwargs) | |
d[key] = value | |
return value | |
return compute | |
@memoize | |
def fib(n, a=1): | |
print "fib(%d)" % n | |
if n < 3: | |
return 1 | |
else: | |
return fib(n-1) + fib(n-2) | |
@compute_once | |
def return_one(): | |
print "Executing" | |
return 1 | |
@compute_once | |
def return_two(): | |
print "Executing" | |
return 2 | |
print fib | |
print fib(10, a=2) | |
print return_one | |
print return_one() | |
print return_one() | |
print return_two() | |
print return_two() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment