🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Recursion: Memoization, Divide and Conquer, Trampolines

Python RecursionđŸŸĸ Free Lesson

Prerequisites

  • !Recursive function basics and base cases
  • !Big-O reasoning for time and space complexity

What You'll Learn

  • 1Explain why CPython hits a recursion limit long before memory runs out
  • 2Add memoization with lru_cache and reason about the resulting complexity
  • 3Structure divide and conquer solutions around a clear merge step
  • 4Convert apparent tail recursion into an iterative trampoline
  • 5Decide when recursion is the wrong tool and flatten it instead

Recursion is the shortest path to a correct solution for tree walking, backtracking, and any problem that decomposes into smaller versions of itself. It is also the fastest way to produce a RecursionError in production if you treat it as free. This lesson covers the three things that separate working recursive code from fragile code: controlling depth, collapsing repeated work with memoization, and escaping the interpreter's stack limits without rewriting your algorithm by hand.

Where CPython actually runs out

The limit you hit first is not memory. CPython refuses to grow the C call stack past a configurable ceiling, currently around one thousand frames by default, precisely to turn a runaway recursion into a clean exception instead of a process crash. Every Python frame carries a local namespace, a code pointer, and bookkeeping for exception handling, so a thousand of them already costs real memory. Raising the ceiling with sys.setrecursionlimit buys headroom, but it does not change the shape of the problem: a linear recursion over a million elements will still fail, and a C-level stack overflow becomes possible if you push far enough.

The practical consequence is that recursion must be justified by structure rather than by convenience. A depth proportional to the height of a tree or the logarithm of the input is safe. A depth proportional to the number of elements is a design smell, and the fix is either memoization that prevents re-descending, or an explicit stack that the heap manages for you.

Memoization: paying once for each distinct subproblem

The classic fibonacci example is exponential because the same indices are recomputed on every branch. Adding a cache changes the complexity class, not just the speed, because each distinct argument is evaluated exactly once.

python
from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(90))   # 2880067194370816120

def memoize(func):
    cache = {}

    def wrapper(*args):
        if args not in cache:
            cache[args] = func(*args)
        return cache[args]

    return wrapper

@memoize
def edit_distance(a, b, i=None, j=None):
    i = len(a) if i is None else i
    j = len(b) if j is None else j
    if i == 0 or j == 0:
        return i + j
    if a[i - 1] == b[j - 1]:
        return edit_distance(a, b, i - 1, j - 1)
    return 1 + min(
        edit_distance(a, b, i - 1, j),
        edit_distance(a, b, i, j - 1),
        edit_distance(a, b, i - 1, j - 1),
    )

print(edit_distance("kitten", "sitting"))   # 3

Memoization only works when arguments are hashable and the function is pure. Give it a list argument and you get a TypeError; give it a function that reads global state and the cache will happily return stale answers. The hand-written wrapper above shows the mechanism so you can see both limits; in application code, prefer lru_cache or cached_property-style helpers unless you need custom eviction.

Problem shapeUnmemoised costMemoised costTypical examples
Overlapping subproblemsExponential in nLinear in statesFibonacci, edit distance
Distinct subproblems onlyLinearLinear plus cache overheadPlain tree walk
Search with pruningExponential worst caseDepends on pruningSudoku, N-queens
Deep linear chainLinear time, linear stackNo benefitRunning totals

Divide and conquer with a merge you can trust

A divide and conquer solution is three decisions in a trench coat: how to split, when to stop, and how to recombine. Merge sort is the cleanest teaching example because the split is trivial, the base case is a single element, and the merge is where all the correctness lives.

python
def merge_sort(items):
    if len(items) <= 1:
        return items

    mid = len(items) // 2
    left = merge_sort(items[:mid])
    right = merge_sort(items[mid:])
    return merge(left, right)


def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result


print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
# [3, 9, 10, 27, 38, 43, 82]

Two properties make this trustworthy. The recursion halves the input each level, giving depth logarithmic in the length, which is far below any limit. And each level does work proportional to the input size, so the total is n log n regardless of the order of the data. When you adapt the pattern to your own problem, write the merge as a separate function with its own tests; that is where off-by-one errors hide.

Tail position without tail call optimization

Python deliberately does not perform tail call optimization, so rewriting a recursion so the recursive call is the last expression changes nothing about stack growth. What you can do is bounce the call through a loop: instead of calling yourself, return a thunk, and let a driver loop invoke it. That technique, the trampoline, keeps depth at one frame however many steps the computation takes.

python
def trampoline(step, *args):
    result = step(*args)
    while callable(result):
        result = result()
    return result


def sum_to(n, acc=0):
    if n <= 0:
        return acc
    return lambda: sum_to(n - 1, acc + n)


print(trampoline(sum_to, 100000))   # 5000050000

The trade-off is readability: the thunk version is harder to follow than the direct one. Reach for the trampoline only when you have measured a genuine depth problem and want to keep the recursive formulation. Otherwise, convert the algorithm to a plain loop with an explicit accumulator and move on.

Choosing between recursion, iteration, and a stack

There is no prize for the most recursive solution. Trees and graphs with unbounded depth are natural recursion territory because the structure itself defines the base case. Sequences with a known length are usually clearer as loops. Backtracking needs recursion or an explicit stack, and an explicit stack is often easier to instrument because you can print its contents.

SituationPreferred shapeWhy
Tree or DAG traversalRecursionDepth follows structure, not input size
Linear sequence of a million itemsLoopConstant memory, no limit risk
Backtracking searchRecursion with pruningUndo state for free on the way back
Parser over nested inputRecursionGrammar depth is usually small
Any hot path called millions of timesIterationFrame overhead dominates

Whichever you choose, keep the invariant visible in a docstring: what the function assumes on entry and guarantees on exit. Recursive code is correct when the base case is right, the recursive call strictly approaches the base case, and the combination step preserves the guarantee.

Backtracking: recursion that undoes its own choices

Some problems cannot be decomposed into independent subproblems; they require trying a choice, exploring its consequences, and then reversing the choice when it fails. N-queens, Sudoku, word puzzles, and path searches with constraints all share this shape, and recursion expresses it directly because returning from a frame is the natural undo operation. An explicit loop version must push and pop state by hand, which is where most bugs appear.

The discipline in a backtracking routine is to restore invariants before returning, not after. If you prune a branch, the shared board or path must look exactly as it did before the recursive call, otherwise later branches inherit corruption that produces plausible-looking but wrong answers. Pruning is what keeps the search tractable: rejecting a partial assignment as soon as it violates a constraint can cut millions of nodes from the tree, and it is the difference between a solver that finishes in seconds and one that never returns.

Depth in these searches follows the number of decisions, which is usually small enough to be safe, but the branching factor is the real danger. Track nodes visited with a counter and assert a ceiling in tests so a regression in pruning fails loudly instead of hanging a build. The same counter doubles as a profile: if it explodes after a small change to the constraint function, you have found your bug.

Backtracking elementPurposeCommon mistake
Choose stepMakes one decision and records itForgetting to record the choice
Explore stepRecurses on the smaller problemPassing a copy that hides state
Unchoose stepRestores the invariant before returningRestoring only on the success path
Prune testRejects impossible partial states earlyTesting too late to help
Depth counterGuards against runaway searchOmitting it entirely

Common Mistakes

Raising sys.setrecursionlimit to ten million and hoping for the best

Fix: Leave the limit alone and change the algorithm: memoize, flatten to a loop, or walk with an explicit stack.

Memoizing a function that takes unhashable or mutable arguments

Fix: Convert arguments to a hashable key such as a tuple, or cache on a canonical identifier instead.

Writing a recursive call that does not shrink the problem

Fix: Assert in a test that each recursive invocation reduces the distance to the base case.

Expecting a tail-recursive rewrite to save stack in Python

Fix: Use a trampoline loop or convert to iteration, because CPython performs no tail call optimization.

Best Practices

  • Name the invariant of every recursive helper in its docstring
  • Keep base cases at the top of the function where a reader can verify them first
  • Add a depth guard in tests so accidental exponential depth fails fast
  • Separate the merge or combine step into its own testable function
  • Profile before adding a cache; a cache costs memory and a hash computation per call

Key Takeaways

  • CPython stops recursion at a frame limit to protect the C stack, so depth must follow structure
  • Memoization converts exponential overlap into linear work for pure functions with hashable inputs
  • Divide and conquer stays fast when the split halves the input and the merge is linear
  • Trampolines emulate tail call optimization by bouncing thunks through a loop
  • For long linear work, a plain loop with an accumulator beats recursion every time
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement