Predict the output
What does this print?
rows, cols = 3, 4
r, c = 0, 3
steps = ((1, 0), (-1, 0), (0, 1), (0, -1))
nbrs = [(r + dr, c + dc) for dr, dc in steps
if 0 <= r + dr < rows and 0 <= c + dc < cols]
print(nbrs)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [(1, 3), (0, 2)]
Right: a corner cell has only two neighbours inside the grid.
Corner cells have two neighbours, edge cells three and inner cells four, which is why edges are at most 4·R·C.
Why not the others?
- B [(1, 3), (-1, 3), (0, 4), (0, 2)]. The bounds check removes cells outside the grid.
- C [(1, 3)]. Moving left to (0, 2) stays inside the grid.