best cumulative sum

Peter Otten __peter__ at web.de
Wed Nov 23 13:09:33 EST 2005


David Isaac wrote:

> def ireduce(func, iterable, init=None):
>     if init is None:
>         iterable = iter(iterable)
>         init = iterable.next()
>         yield init
>     elif not iterable:

You are in for a surprise here:

>>> def empty():
...     for item in []:
...             yield item
...
>>> bool(empty())
True

>>> bool(iter([]))
True # python 2.3 and probably 2.5

>>> bool(iter([]))
False # python 2.4

>         yield init
>     for item in iterable:
>         init = func(init, item)
>         yield init

Peter




More information about the Python-list mailing list