Personal website Rudolf Adamkovič

Home / Computer science / Memoization


Manual memoization in Python

# Memoized results.
ys = {}


def f(n):
    """Return the factorial."""

    # Check preconditions.
    assert int(n) == n, "Factorial of non-integral values is undefined"
    assert n >= 0, "Factorial of negative integers is undefined"

    # Return early in the base case.
    if n == 1:
        return 1

    # Return early with a memoized result.
    if n in ys:
        return n

    # Compute the result.
    y = n * f(n - 1)

    # Memoize the result.
    ys[n] = y

    # Return the result.
    return y


# Try it.
f(5)
120

© 2025 Rudolf Adamkovič under GNU General Public License version 3.
Made with Emacs and secret alien technologies of yesteryear.