Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 69 / 101

Do the work once.

Recognise overlapping subproblems and avoid recomputing the same answer.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Dynamic programming saves results of overlapping subproblems. Top-down memoization adds a cache to a recursive solution; bottom-up tabulation fills results in an order where dependencies are already available. The technique requires a well-defined state and a recurrence. Caching arbitrary code is not automatically correct, especially when results depend on changing external data.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

dynamic_programming.py
from functools import lru_cache
@lru_cache(maxsize=None)
def ways(steps):
    if steps < 0: return 0
    if steps == 0: return 1
    return ways(steps - 1) + ways(steps - 2)
print(ways(5))
print(ways.cache_info().currsize)
↳ EXPECTED OUTPUT
8
7

03 Under the hood

  1. 1

    ways(n) counts routes using one- or two-step moves. The two base cases define a valid empty route and impossible negative routes.

  2. 2

    Without caching, many calls repeat. The cache stores each distinct integer state, reducing the number of evaluated states to linear growth here.

  3. 3

    A bottom-up version can keep only the two most recent values, using constant auxiliary storage. Choose a state that captures everything the answer depends on, and account for potentially large integer arithmetic in detailed performance analysis.

04 Your turn, builder

A SMALL MISSION

Implement the same count bottom-up with two running values.

Reveal one possible solution +
one_possible_solution.py
def ways(steps):
    if steps < 0: return 0
    previous, current = 1, 1
    for _ in range(steps):
        previous, current = current, previous + current
    return previous
print(ways(5))

05 Check your signal

QUICK SIGNAL CHECK

What makes memoization useful here?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.