Created
January 29, 2013 07:24
-
-
Save trtg/4662449 to your computer and use it in GitHub Desktop.
dynamic programming in python using the @lru_cache decorator
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
#from functools import lru_cache#python >=3.2 | |
from functools32 import lru_cache#python 2.7 | |
#from repoze.lru import lru_cache#python 2.7 | |
#NOTE: you can use python -m trace --count fibonacci.py | |
#to see how many times each instruction is called | |
#@lru_cache(maxsize=500)#repoze.lru needs maxsize arg | |
@lru_cache()#using functools32 | |
def fibonacci(n): | |
if n<=1: | |
return n | |
return fibonacci(n-1)+fibonacci(n-2) | |
print(fibonacci(100)) | |
#manual dynamic programming way | |
#cache ={0:0,1:1} | |
#def fibonacci(n): | |
# if n in cache: | |
# return cache[n] | |
# cache[n] = fibonacci(n-1)+fibonacci(n-2) | |
# return cache[n] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for the Fibonacci Series, we only need to cache the last two elements. Hence,
@lru_cache(maxsize=2)
would make more sense.