Memoization in Python
Alec Mihailovs
alec at mihailovs.com
Fri Jan 5 04:50:06 EST 2007
Following Antti Karttunen suggestion, I wrote the following simple decorator
for creating functions with cache (something like 'option remember' in
Maple). Just wanted to share it:
def function_with_cache(f):
def new_f(*args):
if args in new_f.cache: return new_f.cache[args]
result=f(*args)
new_f.cache[args]=result
return result
new_f.cache={}
new_f.func_name=f.func_name
return new_f
For example,
@function_with_cache
def A000045(n):
if n<2: return n
return A000045(n-1)+A000045(n-2)
A000045(3)
2
A000045.cache
{(2,): 1, (0,): 0, (3,): 2, (1,): 1}
Or, another example,
@function_with_cache
def binomial(m,n):
if m <0 or n >m: return 0
if n==0 or m==n: return 1
return binomial(m-1,n)+binomial(m-1,n-1)
binomial(5,3)
10
binomial.cache
{(3, 2): 3, (3, 3): 1, (3, 1): 3, (2, 1): 2, (2, 0): 1, (4, 3): 4, (2, 2):
1, (4, 2): 6, (1, 0): 1, (1, 1): 1, (5, 3): 10}
Alec Mihailovs
http://mihailovs.com/Alec/
More information about the Python-list
mailing list