i need to write a function that takes an array of numbers and finds the maximum sum of all the numbers. In other words, I need to find the sum of just the positive numbers. I wrote this, I'm getting "list is out of range"
thoughts?
def maximum_sub(A):
x = 0
i = 0
for i in A:
while A[i] > 0:
x+=A[i]
i+=1
return x
解决方案
Use super functions and list comprehension instead:
>>> a = [1, 2, 3, -4, 5, -3, 7, 8, 9, 6, 4, -7]
>>> sum(x for x in a if x > 0)
45
[x for x in a if x > 0] will create an array made of the positive values in a.
sum(...) will return the sum of the elements in that array.