best cumulative sum

bonono at gmail.com bonono at gmail.com
Tue Nov 22 20:11:05 EST 2005


Michael Spencer wrote:
> David Isaac wrote:
>   for a solution when these are available.
> > Something like:
> > def cumreduce(func, seq, init = None):
> >     """Return list of cumulative reductions.
> >
> >
> This can be written more concisely as a generator:
>
>   >>> import operator
>   >>> def ireduce(func, iterable, init):
>   ...     for i in iterable:
>   ...         init = func(init, i)
>   ...         yield init
>   ...
>   >>> list(ireduce(operator.mul, range(1,5),init=1))
>   [1, 2, 6, 24]
>   >>>
If iterable has no elements, I believe the behaviour should be [init],
there is also the case of init=None that needs to be handled. But
otherwise, that is more or less what I wrote for my scanl/scanl1.

> Michael




More information about the Python-list mailing list