medium +25 pts

Top N per group

Given a list of (group, score) pairs, return the top N scores for each group, sorted descending.

Write a function `top_n_per_group(records, n)` that takes a list of tuples, each containing a group name (string) and a score (integer), and a positive integer `n`. The function should return a dictionary where each key is a group name and the value is a list of the top `n` scores for that group, sorted in descending order. If a group has fewer than `n` scores, include all its scores. If `n` is 0, return an empty dictionary. Groups should appear in the order they first appear in the input. Scores are unique within each group.

Constraints

1 <= len(records) <= 1000; scores are integers; group names are non-empty strings; n >= 0.

Example

>>> top_n_per_group([("A", 10), ("B", 5), ("A", 7)], 1)
{"A": [10], "B": [5]}
>>> top_n_per_group([("x", 1), ("x", 3), ("y", 2)], 2)
{"x": [3, 1], "y": [2]}
>>> top_n_per_group([("g", 4)], 0)
{}
25 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Group the scores by group name, preserving the order of first appearance.
Sort each group's scores in descending order.
Slice the sorted list to get the top n elements.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.