Consider the recursive function below.
def digit_sum(n):
if n < 10:
return n
return n % 10 + digit_sum(n // 10)(a) State the base case. [1]
(b) Show the sequence of calls made by digit_sum(4729). [1]
(c) Show the value returned by each call as the recursion unwinds and state the final result. [2]
(d) State what would happen if the base case were removed. [1]
- (a)
n < 10(a single digit is returned unchanged)(1) - (b) digit_sum(4729) → digit_sum(472) → digit_sum(47) → digit_sum(4)(1)
- (c) digit_sum(4) returns 4; digit_sum(47) returns 7 + 4 = 11; digit_sum(472) returns 2 + 11 = 13(1)
- digit_sum(4729) returns 9 + 13 = 22 (final result 22)(1)
- (d) Infinite recursion: the function keeps calling itself (n // 10 reaches 0 and digit_sum(0) calls digit_sum(0) for ever), so it never terminates / the call stack overflows and a RecursionError is raised (accept any one of: infinite recursion, never stops, stack overflow, RecursionError)(1)
- Answer: (a) n < 10 (b) 4729, 472, 47, 4 (c) 4, 11, 13, 22 (d) RecursionError (stack overflow)
- Examiner tip: Show the value returned at each level as the recursion unwinds, not only the final 22; in (d) say the recursion never stops (stack overflow), not just 'it breaks'.