partial sums problem
nospam at torek.net
Wed Sep 29 08:59:42 CEST 2010
In article <i7trs4$9eq$1 at reader1.panix.com> kj <no.email at please.post> 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,
second call produces vec op vec, third produces
(vec op vec) op vec, and so on.
Mostly useful with + and *, probably.
iterable = iter(vec)
acc = iterable.next()
for x in iterable:
acc = op(acc, x)
"""Return a list of the cumulative sums of a vector."""
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) http://web.torek.net/torek/index.html
More information about the Python-list