Bug hunt

Off-by-One Island

The most common bug in the world is being off by one: a loop that runs one time too many or too few. It hides at the edges.

Remember Python's rules:

  • range(a, b) stops before b. range(1, 4) is 1, 2, 3.
  • items[a:b] stops before index b.
  • The last index is len(items) - 1, so items[len(items)] crashes.

Think of a fence: 4 fence sections need 5 posts. Counting the gaps instead of the posts is called a fencepost error.

The detective trick is to test the edges: an empty list, one item, and the exact first and last values.

The bug report

  • countdown(n) should return [n, n-1, ..., 1]. countdown(3) gives [3, 2].
  • pairs(path) should return each pair of neighbours. For ["dock", "hill", "cave"] that's [("dock", "hill"), ("hill", "cave")]. It crashes with IndexError.

Assignment

Fix one off-by-one bug in each function. countdown(0) should give [], and a path with 0 or 1 places has no pairs ([]).