Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this cumulative sum?

Tags:

python

I'm trying to get [1,3,6] as the result. Am I missing something really obvious? The error I got is: IndexError: list index out of range

def cumulative_sum(n):
    cum_sum = []
    y = 0
    for i in n:
        y += n[i]
        cum_sum.append(y)

    print cum_sum

a = [1,2,3]
cumulative_sum(a)
like image 917
super9 Avatar asked Nov 29 '22 04:11

super9


2 Answers

def cumulative_sum(n):
    cum_sum = []
    y = 0
    for i in n:   # <--- i will contain elements (not indices) from n
        y += i    # <--- so you need to add i, not n[i]
        cum_sum.append(y)
    print cum_sum

a = [1,2,3]
cumulative_sum(a)

Arrays are zero-based in Python, so when you confused n[i] with i, you were accessing n[3] while n only goes from 0 to 2.

like image 50
Ken Bloom Avatar answered Dec 05 '22 02:12

Ken Bloom


The problem is with your loop:

for i in n:
    y += n[i]

The for loop is iterating over the values of n, not the indexes. Change y += n[i] to y += i.

The exception is raised on the third pass through the loop (when i is 3), since 3 is not in the bounds of the array (valid indexes are [0-2]).

If you want to loop over the indexes as well, you can use the built-in enumerate function:

for i, x in enumerate(n):
    assert n[i] == x
like image 45
Cameron Avatar answered Dec 05 '22 02:12

Cameron