best cumulative sum

Peter Otten __peter__ at web.de
Mon Nov 28 03:43:04 EST 2005


bonono at gmail.com wrote:

>> def ireduce(op, iterable, *init):
>>     iterable = chain(init, iterable)
>>     accu = iterable.next()
>>     yield accu
>>     for item in iterable:
>>         accu = op(accu, item)
>>         yield accu

> I believe there is only one initializer in reduce. 

Throw in a 

if len(init) > 1: raise TypeError

for increased similarity to reduce(). 

> Also it is possible to not provide it.

Try it. 

Peter

PS: Did I mention that I prefer for-loops over reduce() most of the time?





More information about the Python-list mailing list