Branching recursion: a function that calls itself twice
Branching recursion is when a function calls itself more than once. Each call starts two smaller calls, so the calls spread out like the branches of a tree, and each branch is smaller than the one it grew from.
Read Recursion: code after the recursive call first.
Two calls in one function
split prints its number, then calls itself twice with a smaller one:
def split(n): if n > 0: print("split", n) split(n - 1) split(n - 1)split(3)It printed 7 lines: split 3, then split 2, split 1, split 1, then
split 2, split 1, split 1. The first split(2) does all its work
before the second split(2) starts.
Every call makes two more, so the calls double at each level: 1, then 2, then 4. That is 7 calls that print.
Shrink by multiplying
The branches of a tree get shorter as they split. To shrink a size, a
recursive call can pass it multiplied by a number below 1:
def shrink(size): if size > 10: print(size) shrink(size * 0.5)shrink(80)It printed 80, 40.0 and 20.0. Each call passes half its own size. The
next size, 10.0, is not more than 10, so that call is the base case and
prints nothing.
Multiplying by 0.5 gives a float, so 40.0 has a decimal point. The size
gets smaller with every call, so the calls always reach the base case. A
function with two calls can pass the smaller size to both.
Come back before the second call
When a turtle function calls itself twice, both calls must start from the same spot. The first call draws, then the second call draws from where the turtle is. So the first call has to leave the turtle where it found it, in the same place and facing the same way.
That works when every call undoes its own moves after its recursive calls:
it turns back by its own turns, then goes backward() along its own line.
You saw this in
Out and back with the turtle.
See also: Recursion in Python: a function that calls itself, Turtle backward(): going back to the start.
Your turn
halves prints its size. Add the two recursive calls, each with
size * 0.5, so halves(40) prints three lines.
40 20.0 20.0
def halves(size): if size > 10: print(size) # add two lines: call halves with size * 0.5, twicehalves(40)