partial sums problem
Ian Kelly
ian.g.kelly at gmail.com
Tue Sep 28 19:52:36 EDT 2010
On Tue, Sep 28, 2010 at 4:57 PM, 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
>
Because in Python assignment is a statement, not an expression.
What's the best way to get a list of partial sums?
>
sum = 0
sums = []
for t in range(1, 10):
sum += t
sums.append(sum)
Or, if you prefer to keep it functional in nature:
def append_sum(sums, x):
return sums + [(sums[-1] if sums else 0) + x]
reduce(append_sum, range(1, 10), [])
Cheers,
Ian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100928/84d144a0/attachment-0001.html>
More information about the Python-list
mailing list