252. Python Program to Rank Students by Percentage
MediumPhase 2 · Practice
This one takes a few steps. Each one uses something you know: split(), a dictionary, a list with sort() and a loop that finds the biggest value.
Overview
Schools often show a rank list after an exam: every student with their percentage, from the best down. It is the same job as a leaderboard, with a fair rule for ties.
Problem Statement
Nadia is a teacher. Every subject in Nadia's exam has the same full marks, and every student takes every subject. The first line of the input gives the full marks per subject and the number of subjects. Then each line holds one student's name and marks, until a line says end.
A student's percentage is their total marks divided by the most marks they could get, times 100. So percentage = total marks ÷ (full marks per subject × number of subjects) × 100.
Print every student from the highest percentage to the lowest, as <rank>. <name> <percentage>%, with 2 decimal places. The ranks follow this rule, as in sports:
- Students with the same percentage share the same rank. List them A to Z by name.
- The rank after a tie skips. If two students share rank 1, the next student has rank 3, because two students are above them.
Examples
Example 1. Input:
50 3
Omar 45 40 50
Bea 30 35 40
Kai 48 47 44
end
gives:
1. Kai 92.67%
2. Omar 90.00%
3. Bea 70.00%
Why: the most marks are 50 × 3 = 150. Kai has 139, and 139 ÷ 150 × 100 = 92.666..., which shows as 92.67. Omar has 135 (90%) and Bea has 105 (70%).
Example 2. Input:
100 2
Zane 80 70
Ana 90 60
Liv 95 90
Ben 50 40
end
gives:
1. Liv 92.50%
2. Ana 75.00%
2. Zane 75.00%
4. Ben 45.00%
Why: Ana and Zane both have 150 of 200 marks, so they share rank 2, with Ana first from A to Z. Three students are above Ben, so Ben's rank is 4, not 3.
Input
The first line holds two whole numbers with a space between them: the full marks of one subject (1 or more), then the number of subjects (1 or more). Then one line per student: a name, then one mark for each subject, all with one space between them. Each mark is a whole number from 0 to the full marks. A name is one word that starts with a capital letter, followed by small letters, and no name appears twice. There is at least one student. The last line is always end. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line per student. The tests try 7 different inputs, also one student, a three-way tie, two ties in a row and a student with 0 marks.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.