Home > Blockchain >  I do not understand how this gives me an error (index error)
I do not understand how this gives me an error (index error)

Time:08-10

I have this function that takes in a sequence as an argument (ar in this case) , such as a list, moves all positive (non negative and no 0) ints/floats from that list into a different list, and then finds the sum of those values.

def positive_sum(ar):
    arrs = 0
    my = []
    for i in range(len(ar) 1):
        if ar[arrs] >0:
            my.append(ar[arrs])
            arrs = arrs 1
        else:
            arrs = arrs 1
    while len(my)!= 1:
        my[0] my[1]
        return my[0]
positive_sum([1,-9,9.5,6,8,2,-10])

After running this, I get an IndexError:

Traceback (most recent call last):
  File "/Users/david/Desktop/Python Coding Files/hello.py", line 27, in <module>
    positive_sum([1,-9,9.5,6,8,2,-10])
  File "/Users/david/Desktop/Python Coding Files/hello.py", line 19, in positive_sum
    if ar[arrs] >0:
IndexError: list index out of range

What is the reason?

CodePudding user response:

def positive(ar):
    my = []
    for i in range(len(ar)):
        if ar[i] > 0:
            my.append(ar[i])
    s = sum(my)
    print(s)
        
positive([1,-9,9.5,6,8,2,-10])

CodePudding user response:

Since you are running the range with extra times, So, when i is 7 the arrs is 7, but the length of your case is only 6. You could achieve by the comprehension expression,

def positive_sum(ar):
    return sum(x for x in ar if x > 0)

positive_sum([1,-9,9.5,6,8,2,-10])
  • Related