So the problem states that given an array of scores, we need to print the first runner up. My analogy is sorting it in a descending fashion and then running a loop that checks for the same numbers at the top and as soon as a number lesser than the highest number(s) is found, printing it.
I'm making use of the while loop and the if statement here. But it's somehow always resulting in an infinite loop. I have alternative solutions but I would really appreciate it if someone shed light on why this specific approach doesn't work.
This is the code:
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
my_list = list(arr)
my_list.sort(reverse = True)
i = 0
while my_list[i] == my_list[i 1]:
continue
i = i 1
if my_list[i] > my_list[i 1]:
print(my_list[i 1])
The input: 2 3 6 6 5
Expected result: 5
CodePudding user response:
Another option is to put your numbers into a set to deduplicate them and then push them through a heapq to get your two top values (then take the 2nd largest value), eg:
import heapq
n = int(input())
assert n > 1
arr = {int(el) for el in input().split()}
print(heapq.nlargest(2, arr)[-1])
CodePudding user response:
You need to remove the continue
statement in your while loop.
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
my_list = list(arr)
my_list.sort(reverse = True)
i = 0
while my_list[i] == my_list[i 1]:
i = i 1
if my_list[i] > my_list[i 1]:
print(my_list[i 1])