In this post, I am going to write a program in python to find the runner-up score which is a hackerrank solution. In other words, we have to find the second largest element in the list in python.
You may be wondering that this is a very easy program. Believe me guys, this is not so simple. Actually, this is a practice program that is given on the Hackerrank website.
In this program, we will read the scores of participants. After that, we will display the runner up the score. Before moving further, let us see the actual outputs that we need.
5 2 3 6 6 5
In the above input, the first line means the number of participants. So there are five participants If we write a program as a beginner, then we will print 6 as the second-largest element because there are two 6s. But the answer is 5.
I hope you got my point. Now, let us see the actual python program.
Python Program to Find the Runner Up Score
n = int(input()) arr = map(int, input().split()) list1 = list(arr) list1.sort(reverse = True) n = len(list1) for i in range(1, n): if list1 != list1[i]: smx = list1[i] break print(smx)
Using the above python program, you can find the runner up score. The first two lines are given in the hackerrank challenge. See the following steps.
- First two lines are reading the inputs.
- The variable n and arr are storing number of participants and their scores respectively.
- In the third line, we are converting arr object to the list using variable list1.
- Now, I have sorted the list in the descending order.
- Using for loop and if statement, I am going to find the runner up score. How? I have already sorted the list in descending order, but there is a possibility that I will get two top scores at the beginning. So, using if statement, I am comparing each and every number that they are same or not. If they are not same, that means I got my output. I will store that value in the variable smx.
I hope you have understood the program. Now, let us see one more input and output for better understanding.
10 6 6 6 6 6 6 6 6 6 5