Adding the current amount to the list in a loop and returning the list:
>>> def running_sum(iterable):
... s = 0
... result = []
... for value in iterable:
... s += value
... result.append(s)
... return result
...
>>> running_sum([1,2,3,4,5])
[1, 3, 6, 10, 15]
Or using yield
statement :
>>> def running_sum(iterable):
... s = 0
... for value in iterable:
... s += value
... yield s
...
>>> running_sum([1,2,3,4,5])
<generator object runningSum at 0x0000000002BDF798>
>>> list(running_sum([1,2,3,4,5]))
[1, 3, 6, 10, 15]
If you are using Python 3.2+, you can use itertools.accumulate
.
>>> import itertools
>>> list(itertools.accumulate([1,2,3,4,5]))
[1, 3, 6, 10, 15]
accumulate
- " ". .