best cumulative sum

Michael Spencer mahs at telcopartners.com
Tue Nov 22 19:58:13 EST 2005


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]
  >>>

Michael





More information about the Python-list mailing list