Predict the result
Use the recursive-sum animation. Predict recursive_sum(4), then step through the Python one line at a time. Explain why recursive_sum(0) stops.
Follow recursive calls down to a base case and back again, then explore how the same idea supports larger applications.
Watch calls build up, reach the base case, then return in reverse order.
1def recursive_sum(n):2 if n == 0:3 return 04 subtotal = recursive_sum(n - 1)5 return n + subtotal B2.4.5: a simple non-branching recursive function. Each call makes at most one recursive call. For non-negative n: O(n) time and O(n) auxiliary call-stack space. A loop can use O(1) auxiliary space.
Use the recursive-sum animation. Predict recursive_sum(4), then step through the Python one line at a time. Explain why recursive_sum(0) stops.
Record n for each active call. Pause at the base case, then predict the values returned as the calls finish.
Write a simple non-branching recursive function. Test its base case and a small input. Explain how each call gets closer to stopping.
Use the quicksort, tree traversal and fractal animations to explain smaller subproblems. These branching examples illustrate applications; their full implementation is not required by B2.4.5.
Compare the recursive sum with a loop. Explain why pending recursive calls require extra memory.
Spend about 3 minutes on each during practice time. Predict, run, change one thing, then explain. These prompts do not add homework.
A starter is runnable code to explore or complete. If the playground restores your saved code, the linked starter is selected in Example: use Load example when ready. Download your work before confirming replacement.
Trace countdown(3). Explain why the call at zero stops.
No imports needed.
A base case stops recursion; each call must move towards it. Use non-negative integers only here.
# A base case stops recursion; each call must move towards it.
def countdown(n):
if n == 0:
return
print(n)
countdown(n - 1)
countdown(3)
Complete the recursive sum for a non-negative integer. Test zero first, then three.
No imports needed.
The recursive result sums smaller numbers; add n to it.
# The recursive result sums smaller numbers; add n to it.
def total(n):
if n == 0:
return 0
return 0 # Your turn: combine n with total(n - 1)
print(total(0), total(3))
What must be true of both the base case and each recursive call for the function to stop?