Skip to content

30. Build Records from CSV Rows

Difficulty: Medium · Topic: OOP & classes

Write a dataclass Trip with fields trip_id: int, city: str, fare: float and tags: list (default: an empty list), plus a class method Trip.from_row(row) that parses a line like "7, Pune ,120.5,airport|night":

Your code runs in CPython on our servers against 6 tests, including hidden ones.

Sample test

Trip.from_row("7, Pune ,120.5,airport|night") == Trip(7, 'Pune', 120.5, ['airport', 'night'])

Expected: True

Hints

Hint 1@dataclass writes __init__, __repr__ and __eq__ from the annotated fields.
Hint 2A mutable default needs field(default_factory=list).
Hint 3@classmethod receives the class as cls; return cls(...) builds the right subclass.

Learn the concepts

More Python problems

All Python problems