Recursion over branches and sequences

Lesson 17 of 20 · Functional Python: values, behavior, and choices

Combine results from branches

A nested tuple can represent a musical phrase: a string is one note, and a tuple groups notes or smaller phrases. We can count notes by adding the counts of every child. This example accepts only strings and finite, acyclic tuples containing the same kinds of values.

def count_notes(phrase):
    if isinstance(phrase, str):
        return 1
    total = 0
    for part in phrase:
        total += count_notes(part)
    return total

phrase = ("C", ("E", "G"), (), "B")
print(count_notes(phrase))
print(count_notes(()))
4
0

Each note returns 1. The inner pair returns 2, the empty tuple’s loop contributes 0, and the outer call combines 1 + 2 + 0 + 1. The string case stops descent at a leaf; an empty tuple also stops without further calls. Unlike a search, aggregation must visit every branch to obtain the complete total. Input validation would be needed for arbitrary values.

Advance through two sequences together

Suppose two lists contain instrument names and their section labels at matching positions. This recursive function produces a dictionary by pairing each position. It rejects unequal lengths instead of silently losing a trailing item. Names must be unique and hashable; otherwise repeated names overwrite earlier entries or unhashable names raise an error.

def pair_sections(names, sections):
    if len(names) != len(sections):
        raise ValueError("sequences must have equal lengths")

    def pair_from(index):
        if index == len(names):
            return {}
        remaining = pair_from(index + 1)
        remaining[names[index]] = sections[index]
        return remaining

    return pair_from(0)

print(pair_sections(["flute", "viola", "horn"], ["wind", "strings", "brass"]))
print(pair_sections([], []))
try:
    pair_sections(["flute"], [])
except ValueError as error:
    print(error)
{'horn': 'brass', 'viola': 'strings', 'flute': 'wind'}
{}
sequences must have equal lengths

The index moves from 0 to 3, where the empty dictionary is returned. As calls resume, they add horn, then viola, then flute, so insertion order in the output is reversed even though the correct positions are paired. This local mutation builds a fresh result without changing either input. A loop or dict(zip(names, sections)) after checking lengths is usually simpler for flat sequences; zip alone stops at the shorter input.

Stop a search early

For a sorted sequence, binary search can discard half of the remaining interval at each step. Here low and high bound a half-open interval: low is included, high is excluded. The changing bounds carry the remaining search state between calls.

def locate_pitch(pitches, target, low, high):
    if low >= high:
        return None
    middle = (low + high) // 2
    if pitches[middle] == target:
        return middle
    if target < pitches[middle]:
        return locate_pitch(pitches, target, low, middle)
    return locate_pitch(pitches, target, middle + 1, high)

pitches = [48, 55, 60, 67, 72]
print(locate_pitch(pitches, 48, 0, len(pitches)))
print(locate_pitch(pitches, 61, 0, len(pitches)))
0
None

For 48, the first middle is index 2 (60), so the next interval is [0, 2); then index 1 is too large and index 0 matches. An empty interval returns None. Check a returned index with is not None: index 0 is valid but falsey. The input must be sorted in ascending order, and bounds must describe a valid interval. With duplicates, this finds a matching index, not necessarily the first. Unlike aggregation, a match returns immediately rather than visiting all remaining elements.

Each active call has a frame containing local information and a point to resume; frames form the call stack. Python limits recursion depth and raises RecursionError when it is exceeded. Python does not eliminate tail calls; blindly raising the limit can exhaust underlying resources. For deep or cyclic input, use a loop with an explicit stack of pending nodes and, when necessary, track visited object identities. Flat sequences often need only a loop or a built-in function.

Chapter index