Last active
August 2, 2016 07:21
-
-
Save louisswarren/bff3586c8aa2748946d2ea3e11704059 to your computer and use it in GitHub Desktop.
MEMEoisation (hardy har har)
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 meme(f): | |
memes = {} | |
def inner(*args, **kwargs): | |
key = (args, tuple(sorted(kwargs.items()))) | |
if key in memes: | |
return memes[key] | |
ret = f(*args, **kwargs) | |
memes[key] = ret | |
return ret | |
return inner | |
@meme | |
def fib(n): | |
if n <= 2: | |
return 1 | |
return fib(n - 2) + fib(n - 1) | |
assert(fib(20) == 6765) | |
# Executes quickly | |
print(fib(100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment