best cumulative sum

David Isaac aisaac0 at verizon.net
Mon Nov 21 14:52:12 EST 2005


> Alan Isaac wrote:
>> Like SciPy's cumsum.


"Colin J. Williams" <cjw at sympatico.ca> wrote in message
news:rvngf.2987$gK4.200074 at news20.bellglobal.com...
> Doesn't numarray handle this?

Sure.
One might say that numarray is in the process of becoming scipy.
But I was looking for a solution when these are available.
Something like:
def cumreduce(func, seq, init = None):
    """Return list of cumulative reductions.

    Example use:
    >>> cumreduce(operator.mul, range(1,5),init=1)
    [1, 2, 6, 24]
    >>>

    :author: Alan Isaac
    :license: public domain
    """
    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





More information about the Python-list mailing list