best cumulative sum

David Isaac aisaac0 at verizon.net
Wed Nov 23 12:55:19 EST 2005


"Peter Otten" <__peter__ at web.de> wrote in message
news:dm263o$b8b$02$1 at news.t-online.com...
> 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





More information about the Python-list mailing list