Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

python - 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), ))
question from:https://stackoverflow.com/questions/65850782/how-to-prevent-indexerror-list-index-out-of-range

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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), ))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...