Skip to content

Instantly share code, notes, and snippets.

@trtg
Created January 29, 2013 07:24
Show Gist options
  • Save trtg/4662449 to your computer and use it in GitHub Desktop.
Save trtg/4662449 to your computer and use it in GitHub Desktop.
dynamic programming in python using the @lru_cache decorator
#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]
@ranafge
Copy link

ranafge commented Jun 19, 2015

when i run this program it take time and at last occur an error.

@andiac
Copy link

andiac commented Jan 7, 2020

maybe we need @lru_cache(maxsize=None) ?

@vaibkumr
Copy link

vaibkumr commented Jan 2, 2021

maybe we need @lru_cache(maxsize=None) ?

for the Fibonacci Series, we only need to cache the last two elements. Hence, @lru_cache(maxsize=2) would make more sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment