Re: best cumulative sum




"Peter Otten" <__peter__@xxxxxx> wrote in message
news:dm263o$b8b$02$1@xxxxxxxxxxxxxxxxxxxx
> Of course nothing can beat a plain old for loop in terms of readability
and
> -- most likely -- speed.

Here are two versions, meant to be comparable.
Thanks,
Alan Isaac

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

def ireduce(func, iterable, init=None):
if init is None:
iterable = iter(iterable)
init = iterable.next()
yield init
elif not iterable:
yield init
for item in iterable:
init = func(init, item)
yield init


.



Relevant Pages

  • Re: What are your favorite Ruby features?
    ... def foo(bar) ... Syntax isn't all there is to readability. ...
    (comp.lang.ruby)
  • Re: What about a series type?
    ... On 6/7/07, Robert Dober wrote: ... > def initialize ... > @init = init ... puts s1.get_some ...
    (comp.lang.ruby)
  • Re: What about a series type?
    ... def initialize ... @init = init ... puts s1.get_some ...
    (comp.lang.ruby)
  • Re: Creating new types and invoking super
    ... def _init: ... return _init ... This kind of approach can't work, you need to call super(A, obj). ... -- Guilherme H. Polo Goncalves ...
    (comp.lang.python)
  • Re: main window in tkinter app
    ... It might have hit me if the fault was related to someting in baseclass.__initnot taking place, but the recursion loop didn't give me a clue. ... Any idea why failing to init the base class caused the loop? ... var=1 def __init__: pass def getval: return self.var ... As you'd logically expect, if you don't define a function in a derived class but call it ), it will call the method from the base class. ...
    (comp.lang.python)