[Tutor] Memoizing ...
Gregor Lingl
glingl@aon.at
Fri Jun 20 13:21:02 2003
Lloyd Kvam schrieb:
> This is in the Python Cookbook in the Algorithms chapter (17.7).
Thanks for this very valuable hint.
My simplified version looks like this:
class Memoize:
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, *args):
if args not in self.memo:
self.memo[args] = self.fn(*args)
return self.memo[args]
It work's well for my purposes.
Alas! It doesn't compute others than the first few
values of the ackermann-function, which seems to be
such a weird beast beause of calling itself with
growing arguments via calling itself as an argument
of itself.
Nevertheless it would be interesting - even if completely
useless (!) - if anybody could compute ackermann(4,1)
or ackermann(4,2) with Python - the last one having
more than 19000 digits, as somone told me, thus beeing
an ideal task for Pythons long int arithmetics
;-)
Gregor
>
> A Memoize class creates instances that are built to memoize (is this
> still English?)
> the function args and return values. The args become the dictionary
> keys and
> the function return values are the dictionary values. The instance
> tries to return
> the values from its dictionary. If it can't, it calls the original
> function, adds
> to the dictionary, and then returns the function result.
>
> (Page 521 in my copy.)
>
> Gregor Lingl wrote:
>
>> I mean, I'd like to get something like:
>>
>> >>> BINOMM = memoize(BINOM)
>>
>> or
>>
>> >>> BINOMM = memoize(BINOM, BINOM.binom)
>>
>> or something similar.
>>
>> Gregor
>>
>>
>>
>> _______________________________________________
>> Tutor maillist - Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>