By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,621 Members | 1,104 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,621 IT Pros & Developers. It's quick & easy.

Memoization in Python

P: n/a
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/


Jan 5 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
At Friday 5/1/2007 06:50, Alec Mihailovs wrote:
>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...mentation.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

Jan 5 '07 #2

P: n/a
"Gabriel Genellina" <ga******@yahoo.com.arwrote
>
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...mentation.html)
you can improve it so the decorated function looks more like the original.
Thank you very much. Both references are very useful.

Alec
Jan 6 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.