partial sums problem
Chris Torek
nospam at torek.net
Wed Sep 29 02:59:42 EDT 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[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 = iterable.next()
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) http://web.torek.net/torek/index.html
More information about the Python-list
mailing list