r/pythonhelp • • Jan 10 '21

Need help with this question

Hey, I've got this question and I'm not sure how to approach it:

Given a list of numbers and a number called 'initial_sum', the function (called 'culmulative_sum(lst, initial_sum=0)') calculates recursively the cumulative sum of each index with the initial_sum and returns a list of the cumulative sums of each index of the list.

For example, if the input is: [0, 1, 2, 3, 4], 0
The function will return: [0, 1, 3, 6, 10]
Explanation: the 4th element is 6 because 0+0+1+2+3=6

if the input is: [2, 0, 0, 0, 2], 1
The function will return: [3, 3, 3, 3, 5]
Explanation: the 3rd element is 3 because 1+2+0+0=3

Notes: the function has to work recursively, and the time complexity has to be O(n), where n is the length of the list.

Any help?

3 Upvotes

1 comment sorted by

1

u/caporalfourrier Jan 10 '21 edited Jan 10 '21
from itertools import accumulate
cumulative_list(accumulate(initial_list))

However, this is the easy way of doing this and I assume your instructor probably hasn't taught you this and probably never will. What they want you to learn is how to actually program so for that you'll have to use something like this:

def cumulative_sum(list):
    total=0 
    for k in list:     
        total+= k 
        yield total

global scope

list(cumulative_sum(initial_list))