Created
March 9, 2011 01:53
-
-
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.
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
"""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