best cumulative sum

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


"Peter Otten" <__peter__ at web.de> wrote in message
news:dmcvtp$s6s$02$1 at news.t-online.com...
> sufficiently similar

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

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

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.

Thanks,
Alan

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





More information about the Python-list mailing list