best cumulative sum

Peter Otten __peter__ at web.de
Wed Nov 23 17:41:46 CET 2005


[David Isaac]

> def cumreduce(func, seq, init = None):
>     if not seq:
>         cr = [init]*bool(init)
>     else:
>         cr = [seq[0]] * len(seq)
>         if init:
>             cr[0] = func(cr[0],init)
>         for idx in range(1,len(seq)):
>             cr[idx] = func(cr[idx-1],seq[idx])
>     return cr

[Michael Spencer]

> >>> import operator
> >>> def ireduce(func, iterable, init):
> ...     for i in iterable:
> ...         init = func(init, i)
> ...         yield init
> ...

[David Isaac]

> Right.  So it is "more concise" only by being incomplete, right?
> What other advantages might it have?
 
- allows arbitrary iterables, not sequences only
- smaller memory footprint if sequential access to the items is sufficient
- fewer special cases, therefore
- less error prone, e. g. 
   + does your implementation work for functions with 
     f(a, b) != f(b, a)?
   + won't users be surprised that 
     cumreduce(f, [1]) == cumreduce(f, [], 1)
     !=
     cumreduce(f, [0]) == cumreduce(f, [], 0)

Of course nothing can beat a plain old for loop in terms of readability and
-- most likely -- speed.

Peter




More information about the Python-list mailing list