best cumulative sum

bonono at gmail.com bonono at gmail.com
Sun Nov 27 19:44:19 EST 2005


Peter Otten wrote:
> 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
>
I believe there is only one initializer in reduce. Also it is possible
to not provide it.




More information about the Python-list mailing list