Last active
December 22, 2015 19:42
-
-
Save thirdwing/16e121e335d6041a3778 to your computer and use it in GitHub Desktop.
This file contains 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
#!/bin/python | |
from collections import OrderedDict | |
def memo(f, k): | |
cache = OrderedDict() | |
def memoized(n): | |
if n not in cache: | |
cache[n] = f(n) | |
if len(cache) > k: | |
del cache[cache.keys()[0]] | |
return cache[n] | |
return memoized | |
def fib(n): | |
print 'We are computing' | |
if n == 1: | |
return 0 | |
if n == 2: | |
return 1 | |
return fib(n - 2) + fib(n - 1) | |
fib_m = memo(fib, 3) | |
fib_m(3) | |
fib_m(4) | |
fib_m(5) | |
fib_m(6) | |
fib_m(3) | |
fib_m(4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment