Memoization in Python

A

Alec Mihailovs

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/
 
G

Gabriel Genellina

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:

Nice. There is already a memoize decorator in the Python wiki:
http://wiki.python.org/moin/PythonDecoratorLibrary, you can get some
ideas from there. Using the functools module (2.5) or the decorator
module by M. Simoniato
(http://www.phyast.pitt.edu/~micheles/python/documentation.html) you
can improve it so the decorated function looks more like the original.


--
Gabriel Genellina
Softlab SRL






__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
 
A

Alec Mihailovs

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top