best cumulative sum

David Isaac aisaac0 at
Mon Nov 28 19:05:05 CET 2005

"Peter Otten" <__peter__ at> wrote in message
news:dmcvtp$s6s$02$1 at
> sufficiently similar

I think I understand your points now.
But I wanted to match these cases:

>>> import operator
>>> reduce(operator.add,[],42)
>>> reduce(operator.add,[1],42)

The idea is that the i-th yield of i-reduce shd be the
result of reduce on seq[:i] with the given initializer.

That said, for the applications I first intended,
yes it is sufficiently similar.  For now, I'll stick
with the version below.


def ireduce(func, iterable, init=None):
    iterable = iter(iterable)
    if init is None:
        init =
        yield init
            init = func(init,
            yield init
        except StopIteration:
            yield init
    for item in iterable:
        init = func(init, item)
        yield init

More information about the Python-list mailing list