partial sums problem

Chris Torek nospam at
Wed Sep 29 08:59:42 CEST 2010

In article <i7trs4$9eq$1 at> kj  < at> wrote:
>The following attempt to get a list of partial sums fails:
>>>> s = 0
>>>> [((s += t) and s) for t in range(1, 10)]
>  File "<stdin>", line 1
>    [((s += t) and s) for t in range(1, 10)]
>          ^
>SyntaxError: invalid syntax
>What's the best way to get a list of partial sums?

Well, define "best"; but curiously enough, I wrote this just a few
days ago for other purposes, so here you go, a slightly cleaned-up /
better documented version of what I wrote:

def iaccumulate(vec, op):
    """Do an accumulative operation on a vector (any iterable, really).

    The result is a generator whose first call produces vec[0],
    second call produces vec[0] op vec[1], third produces
    (vec[0] op vec[1]) op vec[2], and so on.

    Mostly useful with + and *, probably.
    iterable = iter(vec)
    acc =
    yield acc
    for x in iterable:
        acc = op(acc, x)
        yield acc

def cumsum(vec):
    """Return a list of the cumulative sums of a vector."""
    import operator

    return list(iaccumulate(vec, operator.add))
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)

More information about the Python-list mailing list