reduce()--what is it good for?
Anton Vredegoor
anton at vredegoor.doge.nl
Sat Nov 8 08:36:19 EST 2003
Alex Martelli <aleaxit at yahoo.com> wrote:
>Of course you can memoize any pure function of hashable args. But
>memoizing a recursive implementation of factorial has a nice property,
>shared by other int functions implemented recursively in terms of their
>values on other ints, such as fibonacci numbers: the memoization you do for
>any value _helps_ the speed of computation for other values. This nice
>property doesn't apply to non-recursive implementations.
Maybe we need a better example because it is possible to use reduce on
a function which has side effects.
Anton.
class _Memo:
biggest = 1
facdict = {0 : 1, 1 : 1}
def fac(n):
def mymul(x,y):
res = x*y
_Memo.facdict[y] = res
_Memo.biggest = y
return res
def factorial(x):
b = _Memo.biggest
if x > b: return reduce(mymul, xrange(b+1,x+1), b)
return _Memo.facdict[x]
return factorial(n)
def test():
print fac(5)
if __name__=='__main__':
test()
More information about the Python-list
mailing list