Sub topic 2
Thinking Recursively: Trusting the Smaller Call
This chapter assumes you can read Python functions, lists, and classes, and that you know what a base case and the call stack are from the previous chapter.
The Leap of Faith
To design a recursive function, assume the recursive call already works on the smaller input, then ask how to build the full answer from it. You don't need to trace every call. You need two checks: the base case returns the right answer, and each call moves closer to that base case.
Recursion on Lists and Strings
A list or string splits into a first element and a smaller remainder:
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[0]
print(total([3, 1, 4])) # 8
print(reverse("abc")) # cbaTrust that reverse(s[1:]) reverses the rest. Appending s[0] to that result finishes the job.
Recursion Versus Iteration
A loop computes the same sum without growing the call stack:
def total_iterative(items):
result = 0
for x in items:
result += x
return result
print(total_iterative([3, 1, 4])) # 8| Concern | Recursion | Iteration |
|---|---|---|
| Fits naturally | Nested or self-similar data | Flat sequences |
| Stack use | One frame per call | Constant |
| Hidden cost here | `items[1:]` copies the list on every call, so the sum takes O(n²) time | None |
Tree Recursion
When a function calls itself more than once, the calls branch out into a tree:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55The same subproblems are solved more than once, so the work grows exponentially with n. A later chapter fixes this with memoization.
Recursion on Trees
A binary tree is either empty or a node with two smaller trees under it. The function's structure follows the data's structure:
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
tree = Node(1, Node(2, Node(4)), Node(3))
print(height(tree)) # 3Exercise
Write a recursive function count_nodes(node) that returns the number of nodes in a binary tree built from the Node class above.
Show answer
def countnodes(node): return 0 if node is None else 1 + countnodes(node.left) + count_nodes(node.right). For the example tree it returns 4.
Exercise
Why does total(items) take O(n²) time even though it makes only n recursive calls?
Show answer
Each slice items[1:] copies the rest of the list. The copies cost (n-1) + (n-2) + ... + 1, which is O(n²).