Arsal Abbas - 1 year ago 66
Python Question

# a function that takes a list of integers as a parameter and returns a list of running totals

I have this function in python, and this function computes the sum of the integers in the list.

``````def runningSum(aList):
theSum = 0
for i in aList:
theSum = theSum + i
return theSum
``````

result:

``````>>runningSum([1,2,3,4,5]) = 15
``````

what I'm hoping to achieve from this function is to return a list of running totals.
something like this:

``````E.g.: [1,2,3,4,5] -> [1,3,6,10,15]
E.g.: [2,2,2,2,2,2,2] -> [2,4,6,8,10,12,14]
``````

Appending the running sum into a list in a loop and return 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]))  # Turn the generator into a list
[1, 3, 6, 10, 15]
``````

If you're using Python 3.2+, you can use `itertools.accumulate`.

``````>>> import itertools
>>> list(itertools.accumulate([1,2,3,4,5]))
[1, 3, 6, 10, 15]
``````

where the default operation in `accumulate` with an iterable is 'running sum'. Optionally you can also pass an operator as needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download