Personal website Rudolf Adamkovič

Home / Computer science / Memoization


Automatic memoization in Python

from functools import lru_cache


@lru_cache(maxsize=None)
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"

    # Compute the result.
    return n * f(n - 1) if n else 1


# Try it.
f(5)
120

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