Dataclasses: build a leaderboard
Read the task → edit your code → Run to see the output → Run tests to check your answer.
A dataclass writes the boilerplate for a data-holding class for you. You
declare the fields with type hints and @dataclass generates __init__,
__repr__, and equality:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
p.x # 1
Point(1, 2) == Point(1, 2) # True
No hand-written __init__ — the fields are the constructor.
Your task
Define a Player dataclass with two fields, name: str and score: int.
Then write leaderboard(players) that takes a list of Player objects and
returns the names ranked by score descending, breaking ties by name
ascending.
players = [Player("ana", 30), Player("bob", 50), Player("cy", 30)]
leaderboard(players) # ["bob", "ana", "cy"]
leaderboard([]) # []
Hint: decorate the class with @dataclass. In leaderboard, sort the players
with key=lambda p: (-p.score, p.name) and return p.name for each.
Tests
- rank by score
- empty leaderboard
- single player
- field access
- dataclass equality
✦ Need help with this task?
Sign in or create a free account to get AI help. Free includes a monthly AI allowance.
$ Console output will appear here.