Skip to content

Instantly share code, notes, and snippets.

@avenet
Created December 17, 2014 16:02
Show Gist options
  • Save avenet/7a5131b6ce42cb24324e to your computer and use it in GitHub Desktop.
Save avenet/7a5131b6ce42cb24324e to your computer and use it in GitHub Desktop.
Memoize pattern implementation
def memoize(f):
cache = {}
def decorated(n):
if n in cache:
return cache[n]
else:
cache[n] = f(n)
return cache[n]
return decorated
@memoize
def factorial(n):
if n <= 0:
return 1
return n*factorial(n-1)
@memoize
def fibonacci(n):
if n<=1:
return 1
return fibonacci(n-1)+fibonacci(n-2)
print factorial(5)
print fibonacci(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment