-1

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

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 1
    @Passerby Thank you! I've been using continue as a mechanism to skip that part of code and move on with the rest of the code. I removed continue and the code's working fine now. – noughtsamar Oct 31 '21 at 11:18
  • 1
    Tangentially, the code you put inside `if _ name__ == ’__main__’:` should be absolutely trivial. The condition is only useful when you `import` this code; if all the useful functionality is excluded when you `import`, you will never want to do that anyway. See also https://stackoverflow.com/a/69778466/874188 – tripleee Oct 31 '21 at 11:22

2 Answers2

1

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])
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

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])
Cardstdani
  • 4,999
  • 3
  • 12
  • 31