Recursion · 5 / 18 Theory

Mutual and tail recursion and divide and conquer

Besides simple recursion, there are three variants worth recognizing.

Mutual recursion

Two functions that call each other. Each one solves part of the problem and delegates the rest to the other.

def is_even(n):
    return True if n == 0 else is_odd(n - 1)

def is_odd(n):
    return False if n == 0 else is_even(n - 1)

print(is_even(10), is_odd(7))     # True True

Tail recursion

It makes the recursive call as the last action, carrying the partial result in an argument (an accumulator). In other languages it is optimized and uses no stack; Python does not do it, so it does not avoid the recursion limit, but sometimes the code is clearer.

def factorial(n, accumulated=1):      # "tail" recursion: the result travels in an argument
    if n <= 1:
        return accumulated
    return factorial(n - 1, accumulated * n)

print(factorial(5))                 # 120

Divide and conquer

A problem is divided into smaller subproblems of the same kind, each one is solved recursively and the results are combined. It is the idea behind binary search and fast sorting algorithms.

def maximum(items):
    if len(items) == 1:
        return items[0]
    half = len(items) // 2
    left = maximum(items[:half])      # solve each half...
    right = maximum(items[half:])
    return max(left, right)          # ...and combine

print(maximum([4, 9, 2, 7, 5]))              # 9

You practice it in Recursive binary search. If each subproblem is halved, the depth is only log n levels, which is why Fast exponentiation needs few multiplications.

Building a structure layer by layer

Other times each result is built from the previous one, as in Pascal's triangle.

def row(k):
    if k == 0:
        return [1]
    previous = row(k - 1)
    return [1] + [a + b for a, b in zip(previous, previous[1:])] + [1]

print(row(4))      # [1, 4, 6, 4, 1]

You practice it in Pascal's triangle, and the sum of the digits of a number in Sum of digits.

VariantIdeaExample
SimpleThe function calls itselfFactorial
MutualTwo functions call each otherEven / odd
TailThe call is the last actionFactorial with accumulator
Divide and conquerDivide, solve and combineBinary search