Count the work, not just the seconds.
Reason about growth and compare algorithms before a small timing test misleads you.
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.
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))(True, 8) (True, 16)
03 Under the hood
- 1
The target sits at the end in both examples, exposing a worst-case scan. Doubling the input doubles the number of comparisons.
- 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
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
Count the number of pairs produced by a nested n-by-n loop for n=4 and n=8.
Reveal one possible solution +
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
How does an n-by-n nested loop normally grow?
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 ↗.