Created
March 15, 2014 20:42
-
-
Save chipbell4/9573668 to your computer and use it in GitHub Desktop.
A simple function to wrap a recursive function to make it memoize.
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
def memoize(F): | |
# A hash table for storing previous states | |
hashed_states = {} | |
def memoized_F(*args): | |
# if we haven't memoized this state, calculate | |
# it. Then return it | |
if args not in hashed_states: | |
hashed_states[args] = F(*args) | |
return hashed_states[args] | |
return memoized_F | |
@memoize | |
def fibonacci(N): | |
if N is 0 or N is 1: | |
return N | |
else: | |
return fibonacci(N-1) + fibonacci(N-2) | |
print(fibonacci(100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment