简体   繁体   中英

how to prevent IndexError: list index out of range

this code will give max sum and min sum in a list for input like 1 2 3 4 5 the output is coming properly like 14 10 when i enter these numbers 7 69 2 221 8974 error is coming like this
IndexError: list index out of range i have tried below code

import math
lst = list(map(int,input().strip().split()))
lst1 = sorted(lst)
ls = []
for i in lst1:
    ls.append(math.fsum(lst1)-lst1[i-1])
print(round(min(ls), ),round(max(ls), ))

It's because you are iterating on lst1s values and in your loop, i will contains lists values (in your second example, it will be equal to 7 and then 69 and...). you need to use indexes instead. try this one:

import math
lst = list(map(int,input().strip().split()))
lst1 = sorted(lst)
ls = []
for i,_ in enumerate(lst1):
    ls.append(math.fsum(lst1)-lst1[i])
print(round(min(ls), ),round(max(ls), ))

Firstly and foremost What is max sum and min sum in a list?

Could you explain it better.

ls.append(math.fsum(lst1)-lst1[i-1])

if you alter this line, you won't get such error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM