Find the bug · #56 · Sort and search Easy Python
An empty group crashes the seating planner
A seating planner works out how many ways a group can sit, and an empty group crashes it.
On this page
The report
An event planner shows how many ways a group can be seated in a row. It works for any group, except an empty one: then the page fails with RecursionError.
The code
Read it first: what should it do? Then click the line where you think the bug is.
def arrangements(n):
"""How many ways n people can stand in a line: n! (and 0! is 1)."""
if n == 1:
return 1
return n * arrangements(n - 1)Read it, then pick a line.
Start at 0 and follow the calls: 0, then −1, then −2… When does it stop?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
print(arrangements(4))
try:
print(arrangements(0))
except RecursionError:
print("RecursionError")It prints
24 RecursionError
It should print
24 1
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 stops the recursion only at exactly 1. Starting from 0, the calls go to −1, −2, −3 and never reach 1, so Python eventually raises RecursionError. The base case has to cover every input that should stop, here n <= 1 (0! is 1).
The fix
1def arrangements(n):2 """How many ways n people can stand in a line: n! (and 0! is 1)."""3 if n == 1:3 if n <= 1:4 return 15 return n * arrangements(n - 1)How you’d find it
- Reproduce with the input from the report:
arrangements(0)raisesRecursionError. - A recursion error means the base case is never reached. Trace from 0: it calls itself with −1, then −2.
- The base case checks
n == 1, which 0 jumps straight past.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert arrangements(0) == 1
assert arrangements(1) == 1
assert arrangements(5) == 120Where else this bites
- Any recursion on a size or index: check the smallest and empty inputs first.
- A tree recursion that checks for a leaf but not for an empty tree.