Created
May 30, 2014 15:56
-
-
Save hillscottc/c68a2b85ec2f1bc145d2 to your computer and use it in GitHub Desktop.
Decorator for memoization via 'cache' dictionary.
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(func): | |
"""Decorator for memoization via 'cache' dictionary.""" | |
cache = {} | |
def memoed_func(*args): | |
if args not in cache: | |
cache[args] = func(*args) | |
return cache[args] | |
memoed_func.cache = cache | |
return memoed_func | |
@memoize | |
def fib(n): | |
"""Demos use of memoization decorator. """ | |
if n <= 2: | |
return 1 | |
else: | |
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