简体   繁体   中英

Python - List index out of range

I have been stuck with this question on finding out the second largest number in a list to be read from the console with:

n = size of the list(number of elements) AND arr = The list itself

One of the constraints is -100<=A[i]<=100 which I am unable to integrate within my code as I am getting a LIST INDEX OUT OF RANGE ERROR. For instance, this code fails for the custom input: 3 -10 0 10

but passes for 3 10 0 10

n = int(input())
arr = map(int, input().split())

sortedlist = sorted(arr)
temp = len(sortedlist)

emptylist = []

i = 0 
for temp in range(2, 11):
    if sortedlist[i]<sortedlist[i+1]:
        i+=1
        emptylist.insert(i, sortedlist[i-1])
b = max(emptylist)
print(emptylist)

Error:

Traceback (most recent call last):

File "solution.py", line 12, in if sortedlist[i]

IndexError: list index out of range

if sortedlist[i] < sortedlist[i+1]:

The problem lies here. In your example n = 3 so i can only be 0, 1 or 2. But in your code, i+1 goes 1, 2 and 3 in the above line, which is out of the array bounds.

You can print i and see that i goes till 2 which is n-1 and so i+1 will be out of bounds. That is one easy way you could debug.

You have to ensure a condition where you do not compare with the next element for the last element.

you can just use sortedlist[-2] to get the second largest number.

In case of repeated numbers you have to use set method call over original/sorted list.

sortedlist = sorted(list(set(arr)))

尝试以下代码段number_of_inputs = 4 # this is user defined i = 0 collections = list() while True: user_input = input("Enter your numbers \\n") if 100 >= user_input >= -100: i += 1 collections.append(user_input) if i == number_of_inputs: print "second largest number is \\t ",sorted(collections)[-2] break else: print"this Entry not allowed !!!"

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