Skip to content

Instantly share code, notes, and snippets.

@abehmiel
Forked from eriwen/memoize_decorator.py
Created July 29, 2017 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abehmiel/3d39b3b96e57f09c54b389a924839269 to your computer and use it in GitHub Desktop.
Save abehmiel/3d39b3b96e57f09c54b389a924839269 to your computer and use it in GitHub Desktop.
Memoize Decorator in Python
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