Skip to content

Instantly share code, notes, and snippets.

@en0
Created July 4, 2019 21:13
Show Gist options
  • Save en0/580c4dbfc7ef224045f40ea0674634af to your computer and use it in GitHub Desktop.
Save en0/580c4dbfc7ef224045f40ea0674634af to your computer and use it in GitHub Desktop.
Memorization Decorator
## Generic memorization wrapper
def memorize(fn):
data = {}
def _wrapped_memorize(*args):
key = hash(args)
if key in data:
return data[key]
val = fn(*args)
data[key] = val
return val
return _wrapped_memorize
@memorize
def fib(n):
if n < 0:
raise Exception("Bad Input")
if n == 0 or n == 1:
return n
return fib(n - 1) + fib(n - 2)
print fib(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment