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

Count the work, not just the seconds.

Reason about growth and compare algorithms before a small timing test misleads you.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Complexity describes how resource use grows with input size. Big O expresses an upper growth bound, usually ignoring constant factors. Looking up an item in a hash set is expected constant time, while scanning a list is linear in its length. These are models under assumptions, not guarantees that one tiny program always runs faster on every machine.

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.

complexity.py
def scan(values, target):
    checks = 0
    for value in values:
        checks += 1
        if value == target:
            return True, checks
    return False, checks
print(scan(list(range(8)), 7))
print(scan(list(range(16)), 15))
↳ EXPECTED OUTPUT
(True, 8)
(True, 16)

03 Under the hood

  1. 1

    The target sits at the end in both examples, exposing a worst-case scan. Doubling the input doubles the number of comparisons.

  2. 2

    A scan can finish after one comparison in the best case. State whether your complexity claim concerns best, average, expected, amortised, or worst-case behaviour.

  3. 3

    Space complexity counts extra storage as well. Building a set can make repeated queries faster but costs memory and construction work; that trade-off may be worthwhile only for multiple queries.

04 Your turn, builder

A SMALL MISSION

Count the number of pairs produced by a nested n-by-n loop for n=4 and n=8.

Reveal one possible solution +
one_possible_solution.py
def pairs(n):
    count = 0
    for _ in range(n):
        for _ in range(n): count += 1
    return count
print(pairs(4), pairs(8))

05 Check your signal

QUICK SIGNAL CHECK

How does an n-by-n nested loop normally grow?

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.