Sort students by CGPA from highest to lowest. Students with the same CGPA are listed in alphabetical order of name.
What to build
A sort with two rules.
Requirements
- Sort by CGPA from highest to lowest.
- List equal CGPAs alphabetically by name.
Input
The first line has n (1 to 1000). Each of the next n lines has a name and a CGPA, such as Rahim 3.75.
Output
The names, one per line, in ranked order.
Constraints
n is from 1 to 1000.
Example
Input:
3
Rahim 3.40
Nadia 3.90
Karim 3.60
Output:
Nadia
Karim
Rahim
Why it works
A key that returns a tuple compares its first item first, so the second item only matters for ties. Negating the CGPA reverses one rule without reversing the other.
Examples
Example 1 · Input
3 Rahim 3.40 Nadia 3.90 Karim 3.60
Expected output
Nadia Karim Rahim
Example 2 · Input
2 B 3.50 A 3.50
Expected output
A B
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
sorted(..., key=...) can sort by a tuple.
Hint 2
key=lambda s: (-s[1], s[0]) sorts by CGPA, highest first, then by name.
Solution
Show one correct solution (try it yourself first)
n = int(input())
students = []
for _ in range(n):
name, cgpa = input().split()
students.append((name, float(cgpa)))
for name, cgpa in sorted(students, key=lambda s: (-s[1], s[0])):
print(name)