best cumulative sum

Peter Otten __peter__ at web.de
Sun Nov 27 14:03:46 EST 2005


David Isaac wrote:

> "Peter Otten" <__peter__ at web.de> wrote in message
> news:dm95or$dkt$03$1 at news.t-online.com...
>> I think that the test for an empty iterator makes ireduce() unintuitive.
> 
> OK.
> I misunderstood you point.
> But that is needed to match the behavior of reduce.
>>>> reduce(operator.add,[],42)
> 42

Wouldn't an implementation that gives

list(ireduce(add, [], 42)) --> [42]
list(ireduce(add, [1], 42)) --> [42, 43]
list(ireduce(add, [1, 2], 42)) --> [42, 43, 45]
list(ireduce(add, [])) --> []
list(ireduce(add, [1])) --> [1]
list(ireduce(add, [1, 2])) --> [1, 3]

be sufficiently similar, too? E. g.

from itertools import chain

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

Peter




More information about the Python-list mailing list