—
Trace recursive calls and returns
Tutor me on https://mlprep.iwase.dev/item/prog-rec-digit-sum-trace/. This is a screening item. If window.mlPrepAgent is available, read attempts for item prog-rec-digit-sum-trace before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record with recorded_by agent, include agent_session_id when available, and read it back.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 , including zero. The final sum is .
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'))
Previous attempts
Loading attempts saved in this browser…