Re: best cumulative sum



David Isaac wrote:

> "Peter Otten" <__peter__@xxxxxx> wrote in message
> news:dm95or$dkt$03$1@xxxxxxxxxxxxxxxxxxxx
>> 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

.



Relevant Pages

  • Re: best cumulative sum
    ... > David Isaac wrote: ... >>> I think that the test for an empty iterator makes ireduce() unintuitive. ...
    (comp.lang.python)
  • Re: best cumulative sum
    ... > I think that the test for an empty iterator makes ireduce() unintuitive. ... I misunderstood you point. ... Prev by Date: ...
    (comp.lang.python)