Last active
December 16, 2015 14:58
-
-
Save samartioli/5452095 to your computer and use it in GitHub Desktop.
From the example at: http://ujihisa.blogspot.com/2010/11/memoized-recursive-fibonacci-in-python.html How do I access the cache of fibonacci numbers after running the function?
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
def memoize(f): | |
cache = {} | |
def decorated_function(*args): | |
if args in cache: | |
return cache[args] | |
else: | |
cache[args] = f(*args) | |
return cache[args] | |
return decorated_function | |
@memoize | |
def fib(n): | |
return n if n < 2 else fib(n-2) + fib(n-1) | |
SOLUTION: Assign the local variable to an attribute after the function definition before returning it. | |
def memoize(f): | |
cache = {} | |
def decorated_function(*args): | |
if args in cache: | |
return cache[args] | |
else: | |
cache[args] = f(*args) | |
return cache[args] | |
decorated_function.cache = cache | |
return decorated_function | |
@memoize | |
def fib(n): | |
return n if n < 2 else fib(n-2) + fib(n-1) | |
print fib(10) | |
print fib.cache | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment