best cumulative sum

David Isaac aisaac0 at
Wed Nov 23 18:55:19 CET 2005

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

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

def cumreduce(func, seq, init = None):
    cr = seq[:]
    if not(init is None):
        if seq:
            cr[0] = func(init,seq[0])
            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 =
        yield init
    elif not iterable:
        yield init
    for item in iterable:
        init = func(init, item)
        yield init

More information about the Python-list mailing list