Skip to content

Instantly share code, notes, and snippets.

@shepting
Created March 9, 2011 01:53
Show Gist options
  • Save shepting/861543 to your computer and use it in GitHub Desktop.
Save shepting/861543 to your computer and use it in GitHub Desktop.
Using caching (pseudo dynamic programming) to remove all the redundant calls of a regular recursive Fibonacci program.
"""Calculate the Fibonacci sequence caching the
values after each call.
"""
dp = {}
dp[0] = 0
dp[1] = 1
def fib(n):
# Check for the value, calculate if it's not there
try:
value = dp[n]
except KeyError:
value = fib(n-1) + fib(n-2)
dp[n] = value
return value
# Old way
#return fib(n-1) + fib(n-2)
print fib(40)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment