Skip to content

← Modelling Data with Dataclasses step 9 of 28

Easy Primitives

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 Cell so 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, or None if it never enters a cell twice. Keep a set of the cells seen so far.
  • Keep count_visits and solve as 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 distinct 0, an empty visits list and a first_repeat of None.
  • 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 your first_repeat returned, or None.
  • frozen: True if assigning to a field of a Cell raises FrozenInstanceError.