Debugging recursive programs

Beginner Recursion & structural decomposition
Created by Pavel · 29.04.2026 at 19:04 UTC

Recursive bugs cluster into three buckets: no base case (infinite recursion), wrong combine step (finite but wrong answer), and non-shrinking arguments (you recurse but do not move toward a base). The fastest classroom technique is to trace tiny inputs on paper or in a debugger: arguments should move monotonically toward the base in a dimension you understand (depth, index, numeric size).

logging or targeted print inside a hot recursive function can explode output volume—each frame prints, and exponential algorithms multiply prints further. Prefer unit tests on micro-examples, breakpoints on base-case branches, or a temporary depth counter with a cap.

For data pipelines, reproduce failures on minimal nested payloads: one bad branch in a million-row tree is enough to break aggregation; shrink the JSON until the bug is obvious.

logging how-to: [1].


Sources

University approvals: 0
Tasks
Question 1

Why can unconditional print debugging deep inside a highly branchy recursive function backfire?

Hint

Many calls × many prints.

Question 2

You suspect the base case of a tree visitor never runs. What is the first sanity check?

Hint

Termination needs progress toward a handled case.

Question 3

digits_sum_recursive(n: int) -> int: sum decimal digits for non-negative ints. digits_sum_recursive(0) == 0; if n < 10 return n; else n % 10 + digits_sum_recursive(n // 10). Reject negatives with ValueError.

Hint

Quotient and remainder shrink n toward single-digit base.

Starter code is prefilled; replace TODO blocks with your solution.
2 test cases will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Recursion & structural decomposition
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Pavel
Pavel