# Find the Runner-Up Score!

Given the participants’ score sheet for your University Sports Day, you are required to find the runner-up score. You are given n scores. Store them in a list and find the score of the runner-up.
My Code:
x=int(input())
score = []
y=input()
score = y.split(’ ')
score.sort()
print(score[-2])

I am trying to find the second max value in the list entered by a user, but my code gives a wrong output when the score is repeated.
For Eg:
(In Terminal)
5
1 4 3 2 5
4

Ok, this time it works.

But when someone enters like this:
(In Terminal)
5
1 2 4 5 5
5

But that’s the wrong answer I get, I don’t know how to get the second maximum cause there maybe repeated numbers so my logic fails.

You need to eliminate duplicates before pulling out the runner-up. There are a few ways to do this. I would use a set. Sets don’t have a `sort` method, but you can pass them to the built-in `sorted` function to get a sorted list.

Try this in the shell:

``````>>> y = "1 5 4 2 5"
>>> y.split()
['1', '5', '4', '2', '5']
>>> set(y.split())
{'1', '5', '4', '2'}
>>> sorted(set(y.split())
['1', '2', '4', '5']``````
3 Likes
``````x=int(input())
score = []
list = []
y=input()
score = y.split(' ')
list = sorted(set(score)).copy()
print(list[-2])
``````

My code gives wrong answer whenever there’s a negative input and it gives the wrong answer:
5
-7 -7 -7 -7 -6
-6

But that’s a wrong answer cause -7 should be the answer
Also, it fails when the input is like:
3
50 50 100
100
But that’s a wrong answer cause 100 should be the answer

Yes, you are sorting strings. Another experiment for the shell:

``````>>> sorted(['50','100'])
['100', '50']
>>> sorted([50,100])
[50, 100]``````

You need to convert the ‘number strings’ in `score` to integers first. Try `score = [int(c) for c in y.split()]`.

Why do you copy the sorted list at the end?

Cause score wasn’t remembering the sorting order, so after sorting, I assigned it to list variable.
For Eg.
x=int(input())
score = []
list = []
y=input()
score = y.split(’ ')
list = sorted(set(score)).copy()
print(score[-2])
print(list[-2])

Output:
5
2 2 3 5 4
5
4

Ah, yes. `sorted` doesn’t sort the thing that you pass to it. It creates a new sorted list and returns it. So you don’t need `.copy()` at the end of that line, `sorted` does that already.

A word of caution: `list` is the name of the built-in list type. Never shadow the names of language built-ins! Try to come up with unique identifiers that don’t exist yet.

1 Like