I want to write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].
Here is my code so far:
def count(list1):
x = 0
total = 0
while x < len(list1):
if x == 0:
total = list1[0]
print total
x = x +1
else:
total = list1[x] + list1[x -1]
print total
x = x + 1
return total
print count([1, 2, 3, 4, 7])
However, it is not working.
Can you tell me what I am doing wrong? I worked on this for quite some time now.
You might be over-thinking the process a bit. The logic doesn’t need to really be split up into case tests like that. The part you have right so far is the total counter, but you should only need to loop over each value in the list. Not do a conditional while, with if..else
Normally I wouldn’t just give an answer, but I feel its more beneficial for you to see working code than to try and go through the extra and unnecessary cruft you have so far.
We still use the total counter. And we create an empty list for our results. But all we have to do is loop over each item in the list, add to the total, and append the new value each time. There are no conditionals and you don’t have to worry about when a
whileis going to break. It’s consistant that you will loop over each item in your original list.