Created
July 13, 2010 23:37
-
-
Save eriwen/474749 to your computer and use it in GitHub Desktop.
Memoize Decorator in Python
This file contains hidden or 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(fn): | |
cache = {} | |
def wrapper(*args): | |
try: | |
return cache[args] | |
except: | |
result = fn(*args) | |
cache[args] = result | |
return result | |
return wrapper | |
# Example usage | |
@memoize | |
def fib(n): | |
if n < 2: | |
return n | |
return fib(n - 1) + fib(n - 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment