Created
July 4, 2019 21:13
-
-
Save en0/580c4dbfc7ef224045f40ea0674634af to your computer and use it in GitHub Desktop.
Memorization Decorator
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
## 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