Editor

Top Students in Each Subject

#293 · Working with data · Intermediate · 65 XP · about 12 min

Exam results arrive as (subject, student, mark) tuples. Write top_per_subject(results, n) that returns a dictionary mapping each subject to a list of the names of its n students with the highest marks, best first.

  • If two students in a subject have the same mark, the one that comes first in results ranks higher.
  • A subject with fewer than n results lists all of its students.
  • Put the subjects in the dictionary in alphabetical order.

Examples

results = [
    ('Maths', 'Ana', 91), ('Art', 'Ben', 78), ('Maths', 'Cy', 85),
    ('Maths', 'Dee', 97), ('Art', 'Eve', 88), ('Maths', 'Fin', 60),
]
top_per_subject(results, 2)
# returns {'Art': ['Eve', 'Ben'], 'Maths': ['Dee', 'Ana']}

top_per_subject([('Bio', 'Max', 80), ('Bio', 'Lin', 92), ('Bio', 'Kai', 80)], 2)
# returns {'Bio': ['Lin', 'Max']}

Max and Kai both scored 80, and Max comes first in the list, so Max takes second place.

Constraints

  • 0 <= len(results) <= 100000 and 1 <= n <= 100
  • Marks are whole numbers from 0 to 100, and a student appears at most once per subject.
  • Subject names start with a capital letter followed by lower-case letters.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.