Skip to content

Instantly share code, notes, and snippets.

@chipbell4
Created March 15, 2014 20:42
Show Gist options
  • Save chipbell4/9573668 to your computer and use it in GitHub Desktop.
Save chipbell4/9573668 to your computer and use it in GitHub Desktop.
A simple function to wrap a recursive function to make it memoize.
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