Predicting the outcome of recursive calls
Predicting the outcome helps solidify your understanding of recursion. On this page, you are given recursive function definitions, and you will predict what is printed with various invocations.
Example 1. flow
def flow(num):
if num > 0:
print('before', num)
flow (num - 2)
print('after', num)
else:
print('base case')
Your task:
Predict what the flow
function prints with these invocations (write it down):
flow(4)
You can see the solution for flow(4)
by clicking here.
flow(7)
You can see the solution for flow(7)
by clicking here.
Example 2. chop
Note that chop
has two recursive calls.
def chop(word):
if len(word) > 0:
print(word)
chop(w[1:]) # 1st recursive call
print('---')
chop(w[1:] ) # 2nd recursive call
print('*')
Your task:
Predict what the chop function prints with this invocation:
chop('mat')
Click here for a diagram of the solution using function call frames.
Table of Contents
- Extra Recursion Practice home
- Fruitful recursion w/ Turtle graphics (from lab11)
- Predicting outcome of recursive functions (non-fruitful)
- More practice problems: Recursive Graphics
- More practice problems: More fruitful Turtle Recursion