0

I Have checked other questions similar to this but none of them seem to answer my problem. I need to write a function that returns the cumulative sum of a list of number. I have this but it doesn't seem to work properly:

numbers = [4,3,6]

sums = []

def cumulativeSum(numbers):
    for i in range(len(numbers) - 1):
       sums.append(numbers[i] + numbers[i + 1])
    return sums

print cumulativeSum(numbers)       ##[4, 7, 13] What the answers should come out to be
Marius
  • 58,213
  • 16
  • 107
  • 105
AlexW
  • 1
  • 1
  • 1

2 Answers2

1

This will work, you were never accessing the sum array, which you need to in order to increment the values that you previously calculated and put into it

numbers = [4,3,6]

sums = []

def cumulativeSum(numbers):
    sums.append(numbers[0])
    for i in range(len(numbers) - 1):
        if i == 0:
            sums.append(numbers[i] + numbers[i + 1])
        else:
            sums.append(numbers[i + 1] + sums[i])
    return sums

print cumulativeSum(numbers)
heinst
  • 8,520
  • 7
  • 41
  • 77
1
>>> numbers = [4,3,6]
>>> result = [sum(numbers[:i]) for i in range(1, len(numbers)+1)]
>>> result
[4, 7, 13]
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43
  • This has the same content as the better explained answer from the qn this duplicates - http://stackoverflow.com/questions/15889131/how-to-find-the-cumulative-sum-of-numbers-in-a-list/15889209#15889209 - hence, I recommend deletion – Charles Stewart Dec 02 '14 at 01:23
  • Well my bad, but i did it by myself because the logic make sence. – Tanveer Alam Dec 02 '14 at 01:33
  • There they have used the generator expression which is better in case of large list. It was helpful thanks. – Tanveer Alam Dec 02 '14 at 01:37
  • Tanveer: No fault, just we try to minimise avoidable reduplication. Though it is worth searching a bit to see if there are other useful answers you can link to. – Charles Stewart Dec 02 '14 at 01:44
  • That is very true, but it helps to find our own solution first then dig to search. Because it burns our brain which is helpful. But the reduplication thing is very true. – Tanveer Alam Dec 02 '14 at 01:47