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)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With