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], why don't you trust Python builtins to make their job ? And what isfor temp in range(2, 11):supposed to accomplish ?iis getting incremented every time and you have no checking whether it crossed the list length limit or not==iis not incremented again. Soialways stays 1