
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 beforeb.range(1, 4)is1, 2, 3.items[a:b]stops before indexb.- The last index is
len(items) - 1, soitems[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 withIndexError.
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 ([]).
Fix one off-by-one bug in each function. countdown(0) should give
[], and a path with 0 or 1 places has no pairs ([]).
main.py Python sleeping
Press Run to try your code, then Check to test it.