A function that takes a list of integers as a parameter and returns a list of current totals

I have this function in python and this function calculates the sum of integers in a 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 hope to get from this function is to return a list of current totals. something like that:

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] 
+4
source share
2 answers

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 yieldstatement :

>>> 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 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 - " ". .

+5

def runningSum (aList):   theSum = 0    = []    aList:       theSum = theSum +       cumulative.append(theSum)   

0

Source: https://habr.com/ru/post/1612023/


All Articles