Bug hunt

The Endless Spiral

Every call adds a frame to the call stack, and the stack isn't infinite. Python stops a runaway recursion at about 1000 frames (see sys.getrecursionlimit()) and raises:

RecursionError: maximum recursion depth exceeded

This almost always means one of two bugs:

  1. No base case, so nothing ever stops the calls.
  2. The problem doesn't shrink toward the base case, so the base case is never reached.

The bug report

Both functions below crash with RecursionError:

  • digit_sum(n) should add up the digits of a whole number n >= 0. digit_sum(4321) is 10, and digit_sum(0) is 0.
  • halvings(n) should count how many times you can halve n before reaching 1, using whole-number division. halvings(8) is 3 (8, 4, 2, 1) and halvings(6) is 2 (6, 3, 1).

Assignment

Find and fix one bug in each function.