← Practice
πŸ“– Dataclassesdataclasses-leaderboard
LessonΒ·difficulty 2/5Β·~15 min

Dataclasses: build a leaderboard

Dataclasses: build a leaderboard

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:

python
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.

python
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
  • all tied scores (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.