Created
December 17, 2014 16:02
-
-
Save avenet/7a5131b6ce42cb24324e to your computer and use it in GitHub Desktop.
Memoize pattern implementation
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(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