On Tue, Sep 28, 2010 at 4:57 PM, kj <[email protected]> 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
--
http://mail.python.org/mailman/listinfo/python-list