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.
I tried to arrange n number of scores in a list so that I can select the runner up's score from the list. I expected only the runner up's score but got the whole list as the output.
CodePudding user response:
Some steps to get runner up's score:
- use
sorted()
function to sort the list of score in ascending - After list is sorted, use
pop()
function to remove highest score from the list - use
pop()
again to remove the new last element from the list and stored to new variable. the new variable present as the runner up's score. - Print the runner-up score
Example Code:
# Create a list of scores
scores = [100, 95, 85, 75, 65]
# Sort the list of scores in ascending order
scores = sorted(scores)
# Remove the last element (the highest score) from the list
scores.pop()
# Remove the new last element (the runner-up score) from the list
runner_up_score = scores.pop()
# Print the runner-up score
print(runner_up_score)
CodePudding user response:
sort descending the list first and then pick second item on the list? list[1]
do you have problem on sorting the list or printing the list?
list=[3,0,1,2]
list.sort(reverse=True)
print(list[1])
CodePudding user response:
Note:- Assuming rank is same for same scores
Code:-
#Method 1
#Using remove and find max element
arr = map(int, input("Enter the scores of the students:\n").split())
arr=set(arr)
if arr:
arr.remove(max(arr))
if arr:
print(max(arr))
else:
print("There is no runner up")
#Method2
#Using sort concept with set and list
arr = map(int, input("Enter the scores of the students:\n").split())
arr=list(set(arr))
arr.sort()
if len(arr)>1:
print(arr[-2])
else:
print("There is no runner up")
Output:-
Testcase1: when two possess max score [i.e there are two 1st rankers]
Enter the scores of the students:
89 76 43 68 67 89
76
Testcase2: All scores are different
Enter the scores of the students:
76 89 99 56
89
Testcase3: The scores are all equal.
Enter the scores of the students:
85 85 85 85
There is no runner up
Testcase4 User input only one score.
Enter the scores of the students:
56
There is no runner up
Testcase5 User not input any score.
Enter the scores of the students:
There is no runner up