- Recursion with fractals
Today we will learn to:
- identify the base case and the recursive case of a function
- trace and count the calls of a recursive function
- write a recursive function that draws a fractal
- A function that calls itself
- A recursive function solves a problem by calling itself on a smaller version of it.
- Base case: small enough to answer directly.
- Recursive case: reduce the problem and call again.
- A first example: factorial
def fact(n):
if n == 0:
return 1 # base case
return n * fact(n - 1) # recursive case
4! = 4 × 3 × 2 × 1 = 24
- A recursive tree
To draw a tree:
- draw the trunk
- turn left and draw a smaller tree
- turn right and draw a smaller tree
Stop when the depth reaches 0.
- The tree in code
def tree(length, depth):
forward(length) # draw a branch
if depth > 0: # recursive case
left(25)
tree(length * 0.7, depth - 1)
right(50)
tree(length * 0.7, depth - 1)
left(25)
back(length) # return to the start
- The call tree
- Each call makes 2 more calls, until depth 0.
- Branch tips at depth d: 2d
- Total calls: 1 + 2 + 4 + … + 2d = 2d+1 − 1
- Change the parameters
- Angle: how far the branches spread
- Ratio: how much shorter each level is
- Depth: how many levels
- The Koch curve as a recursive function
def koch(length, n):
if n == 0: # base case
forward(length)
else: # recursive case
koch(length / 3, n - 1); left(60)
koch(length / 3, n - 1); right(120)
koch(length / 3, n - 1); left(60)
koch(length / 3, n - 1)
- Counting calls
- Each call makes 4 calls, until n = 0.
- Segments drawn: 4ⁿ
- Total calls: 1 + 4 + … + 4ⁿ = (4n+1 − 1)/3
- The call stack
- Each unfinished call waits on the call stack.
- The stack depth is the length of one path down the call tree.
koch(…, 5): 1365 calls, but at most 6 on the stack at once.
- Pitfalls
- No base case: the calls never stop.
- The problem never gets smaller: the same thing happens.
- Exponential growth: depth 30 means over a billion tips.
- Your turn: Sierpiński
Write sierpinski(size, n):
- base case: draw a filled triangle
- recursive case: three half-size triangles at the corners
- Summary
- Recursion: a function that calls itself on a smaller problem.
- Always: a base case and progress towards it.
- k calls per level, depth n: kⁿ base cases.
- The stack depth grows with n, the total work with kⁿ.
- Exit question
A recursive function calls itself 3 times until the depth reaches 0.
Called with depth 4, how many base-case calls are there, and how many calls in total?