-
-
Save abehmiel/3d39b3b96e57f09c54b389a924839269 to your computer and use it in GitHub Desktop.
Memoize Decorator in Python
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 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