best cumulative sum
__peter__ at web.de
Wed Nov 23 17:41:46 CET 2005
> def cumreduce(func, seq, init = None):
> if not seq:
> cr = [init]*bool(init)
> cr = [seq] * len(seq)
> if init:
> cr = func(cr,init)
> for idx in range(1,len(seq)):
> cr[idx] = func(cr[idx-1],seq[idx])
> return cr
> >>> import operator
> >>> def ireduce(func, iterable, init):
> ... for i in iterable:
> ... init = func(init, i)
> ... yield init
> 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, ) == cumreduce(f, , 1)
cumreduce(f, ) == cumreduce(f, , 0)
Of course nothing can beat a plain old for loop in terms of readability and
-- most likely -- speed.
More information about the Python-list