We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Modelling Data with Dataclasses step 9 of 28
Count Visited Cells with a Frozen Dataclass
A delivery robot reports the grid cells it drives through, one
Cell(row, col) at a time. You want to know how many different cells it
visited, how often it entered each one, and the first cell it came back to.
Run the starter as it is. count_visits counts the cells in a dictionary
keyed by Cell, and Python stops with a TypeError that says
unhashable type: 'Cell'.
What to write
- Change
Cellso that it can be a dictionary key and a set member, and so that its fields cannot change once you create it. Keep its two fields. - Fill in
first_repeat(path). Return the first cell that the robot enters for the second time, orNoneif it never enters a cell twice. Keep a set of the cells seen so far. - Keep
count_visitsandsolveas they are.
Example
solve(path=[[0, 0], [0, 1], [1, 1], [0, 1], [0, 0]])
# {
# "distinct": 3,
# "visits": [[0, 0, 2], [0, 1, 2], [1, 1, 1]],
# "first_repeat": [0, 1],
# "frozen": True,
# }
The robot enters (0, 1) again at the fourth step, before it enters (0, 0)
again. So first_repeat is (0, 1), not the first cell of the path.
Edge cases
- An empty path gives
distinct0, an emptyvisitslist and afirst_repeatofNone. - Two
Cell(0, 0)objects made separately are the same cell.
What the driver reports
distinct: how many different cells the path holds.visits: one[row, col, count]for each cell, in the order the robot first entered it.first_repeat:[row, col]of the cell yourfirst_repeatreturned, orNone.frozen:Trueif assigning to a field of aCellraisesFrozenInstanceError.
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
Python reference solution
Sign in to track your attempts toward unlocking the reference solution.