To Reduce or Not To Reduce

Gerrit Holl gerrit.holl at pobox.com
Fri Feb 25 07:44:47 EST 2000


Hello,

I thought I finally understood reduce, but apparantly, I don't.

First, I had this code:

>>> def fib(n):
>>>    retval = 0
>>>    for i in range(n):
>>>        retval = retval + i
>>>    return retval

I thought: this must be slow, because it redefines 'retval' for every n.
So I rewrote it using reduce:

>>> def fib(n):
>>>    return reduce(operator.add, xrange(n))

If n is 6, this equals to:
>>> operator.add(operator.add(operator.add(operator.add(1,2),3),4),5)
As I understand it, this does not define a variable every time; so I
exspected it to be faster.

Timing turns out, however, that this version is actually _slower_! Maybe
this is because it has to look up 'add' in another namespace. Getting 'add'
in the local namespace only optimizes it a little bit. Or is it because
of a function call?

What am I missing? When should I use reduce?

regards,
Gerrit.

-- 
Comparison Python GUI's: http://www.nl.linux.org/~gerrit/gui.html
Please comment!




More information about the Python-list mailing list