Trace recursive calls and returns

Problem

For nonnegative integers, digit_sum_trace recursively removes the last digit until one digit remains. Write the exact call and return event order for input 4072, and give the final sum.

Reveal answer or reference solution

Calls descend as 4072, 407, 40, 4. Returns unwind as 4 -> 4, 40 -> 4, 407 -> 11, and 4072 -> 13. The base case is any value less than 1010, including zero. The final sum is 1313.

def digit_sum_trace(n: int) -> tuple[int, tuple[str, ...]]:
    events: list[str] = []
 
    def visit(value: int) -> int:
        events.append(f"call {value}")
        if value < 10:
            result = value
        else:
            result = value % 10 + visit(value // 10)
        events.append(f"return {value} -> {result}")
        return result
 
    total = visit(n)
    return total, tuple(events)

Public tests

  • digit_sum_trace(4072) → (13, ('call 4072', 'call 407', 'call 40', 'call 4', 'return 4 -> 4', 'return 40 -> 4', 'return 407 -> 11', 'return 4072 -> 13'))
  • digit_sum_trace(0) → (0, ('call 0', 'return 0 -> 0'))
Outcome

Previous attempts

Loading attempts saved in this browser…

    Review Screening Results