Sub topic 13
Checking Your Count with a Counter
This chapter assumes you can already derive step counts by hand: single loops, loop bounds, nested and triangular loops, halving loops, and early exits, as covered in earlier chapters. You should also be comfortable writing Python functions and f-strings. Here you will learn to check those derivations by running the code and counting.
A hand-derived formula is a claim about the code. An instrumented counter is a cheap way to test that claim. Off-by-one errors, a < that should have been <=, or a series summed from the wrong starting index all show up right away when you compare a formula against a real count.
The Instrumentation Pattern
To instrument a loop, add a variable that goes up by one each time the operation you care about runs, then return or print that variable. The counter measures exactly what you placed it around, so put the increment where you claimed the "step" happens.
The minimal harness has three parts: an instrumented function, a predicted formula written as a separate function, and a loop that compares the two over many sizes.
def count_pairs(n):
steps = 0
for i in range(n):
for j in range(i + 1, n):
steps += 1
return steps
def predicted_pairs(n):
return n * (n - 1) // 2
for n in (0, 1, 2, 3, 5, 10, 100):
actual = count_pairs(n)
expected = predicted_pairs(n)
status = "ok" if actual == expected else "MISMATCH"
print(f"n={n:4d} actual={actual:6d} expected={expected:6d} {status}")Every row prints ok. Keep the formula in its own function so you can test it on its own. If you only eyeball printed counts, you will miss a mismatch at one awkward size.
Catching an Off-by-One
Halving and doubling loops are where hand derivations slip most often, because "about log2 n" hides whether you need floor, ceiling, or a +1. Consider this loop:
def count_doubling(n):
steps = 0
i = 1
while i < n:
i *= 2
steps += 1
return stepsSuppose your first guess was floor(log2 n). Test it:
import math
def count_doubling(n):
steps = 0
i = 1
while i < n:
i *= 2
steps += 1
return steps
def guess_floor(n):
return math.floor(math.log2(n))
def guess_exact(n):
return (n - 1).bit_length() # equals ceil(log2 n) for n >= 1
for n in range(1, 18):
actual = count_doubling(n)
if actual != guess_floor(n):
print(f"floor guess fails at n={n}: actual={actual}, guess={guess_floor(n)}")
assert actual == guess_exact(n), n
print("exact formula holds for n = 1..17")The floor guess fails at n = 3, 5, 6, 7, 9, and every other size that is not a power of two. The loop stops at the first power of two that is greater than or equal to n, so the count is ceil(log2 n). For n ≥ 1, the integer expression (n - 1).bit_length() gives the same value.
Both formulas are Θ(log n), so the difference does not change the order of growth. It still matters. An exact formula that fails a test means your model of the loop is wrong, and a wrong model will mislead you on harder code.
Counting Several Sites Separately
When a function has sequential blocks, a single counter tells you only the total. Named counters let you check each block's term on its own. A collections.Counter handles this neatly:
from collections import Counter
def process(items, ops):
n = len(items)
total = 0
for x in items:
ops["first_pass"] += 1
total += x
for i in range(n):
for j in range(n):
ops["pair_loop"] += 1
return total
for n in (0, 1, 7, 50):
ops = Counter()
process(list(range(n)), ops)
assert ops["first_pass"] == n
assert ops["pair_loop"] == n * n
print(n, dict(ops))The prediction n + n² passes as a total, and each term also passes on its own. If the total had been wrong, the separate counters would point straight at the block that caused it.
Pass the counter in as an argument instead of using a global. A global counter keeps its old value between calls unless you remember to reset it, and a stale count is a common source of "mismatches" that are not real.
When You Have No Formula: The Doubling Ratio
Sometimes you want the order of growth before you have an exact formula. Run the instrumented code at n, 2n, 4n, and so on, and look at the ratio between successive counts:
| Growth | count(2n) / count(n) as n grows |
|---|---|
| Θ(1) | 1 |
| Θ(log n) | approaches 1 slowly (count rises by a constant) |
| Θ(n) | 2 |
| Θ(n log n) | a little above 2, falling slowly toward 2 |
| Θ(n²) | 4 |
| Θ(n³) | 8 |
def count_single(n):
steps = 0
for i in range(n):
steps += 1
return steps
def count_pairs(n):
steps = 0
for i in range(n):
for j in range(i + 1, n):
steps += 1
return steps
def count_n_log_n(n):
steps = 0
for i in range(n):
j = 1
while j < n:
j *= 2
steps += 1
return steps
sizes = (250, 500, 1000, 2000)
for f in (count_single, count_n_log_n, count_pairs):
counts = [f(n) for n in sizes]
ratios = [counts[k + 1] / counts[k] for k in range(len(counts) - 1)]
print(f.__name__, counts, [f"{r:.3f}" for r in ratios])The linear function gives ratios of exactly 2.000. The pairs function gives 4.008, 4.004, and 4.002, which approach 4 because the −n term in n(n−1)/2 shrinks in relative size. The n log n function gives 2.250, 2.222, and 2.200, since its exact count is n · ceil(log2 n): 2000, 4500, 10000, and 22000.
The ratio test is evidence, not proof. Lower-order terms can hide the true growth at small n, and n log n can look like linear growth with noise. Use it to form a hypothesis, then derive the formula and check it exactly.
Early Exits: Count Over Many Inputs
For a loop that can exit early, a single run produces one count out of a range of possible counts. To check a best-case, worst-case, or average-case claim, run the function over a set of inputs that covers the cases.
def linear_search_steps(items, target):
steps = 0
for x in items:
steps += 1
if x == target:
return steps
return steps
n = 100
data = list(range(n))
counts = [linear_search_steps(data, t) for t in data]
print(min(counts), max(counts), sum(counts) / n) # 1 100 50.5
print(linear_search_steps(data, -1)) # 100The minimum confirms the best case of 1 step, and the maximum confirms the worst case of n steps for a successful search. A failed search also takes n steps. The average over all successful targets is (n + 1)/2 = 50.5, which matches the arithmetic series. That average assumes every target is equally likely, so state that assumption whenever you report an average.
What a Counter Cannot See: Hidden Loops
A counter placed in your code counts only your code. In the function below, a counter in the loop body would report len(a) steps, but the in test scans the list b each time:
def common_items(a, b):
result = []
for x in a:
if x in b:
result.append(x)
return resultOne way to see inside the built-in is to make the elements count their own comparisons. List membership and set lookup both call __eq__ to compare elements, so a class that counts __eq__ calls exposes the hidden work:
class Counted:
comparisons = 0
def __init__(self, value):
self.value = value
def __eq__(self, other):
Counted.comparisons += 1
return self.value == other.value
def __hash__(self):
return hash(self.value)
def common_items(a, b):
return [x for x in a if x in b]
def common_items_fast(a, b):
b_set = set(b)
return [x for x in a if x in b_set]
n = 100
a = [Counted(i) for i in range(n)]
b = [Counted(i) for i in range(n)] # equal values, distinct objects
Counted.comparisons = 0
common_items(a, b)
print("list:", Counted.comparisons) # list: 5050
Counted.comparisons = 0
common_items_fast(a, b)
print("set:", Counted.comparisons) # set: 100With the list, finding value k scans k + 1 elements, so the total is 1 + 2 + … + n = n(n + 1)/2 = 5050, which is Θ(n²). With the set, each lookup goes to the right hash bucket and makes one equality check, so the total is n = 100. Building the set costs one pass over b, and that pass makes no __eq__ calls here because all the hashes are distinct.
Counting Versus Timing
You could check growth with time.perf_counter or timeit instead. Timing includes the hidden loops automatically, but it also includes cache effects, interpreter overhead, garbage collection, and other processes on the machine. Step counts are exact and repeatable, but they include only what you instrumented.
| Method | Strengths | Weaknesses |
|---|---|---|
| Instrumented counter | Exact, deterministic, tests formulas precisely | Misses work you did not instrument; counter adds overhead |
| Wall-clock timing | Captures all real cost, including built-ins | Noisy; needs repeats and large n; machine-dependent |
Use counters to check your derivation. Use timing to check that the derivation counted the right things. If counts grow linearly and times grow quadratically, look for a hidden loop.
Common Mistakes When Instrumenting
- Putting the increment outside the inner loop, so the counter measures outer iterations instead of total steps.
- Putting the increment after a
breakorcontinue, so skipped iterations are not counted. - Reusing a global counter without resetting it between runs.
- Testing only "nice" sizes such as powers of two, which hides floor and ceiling errors.
- Leaving instrumentation in production code. The extra increment and the dictionary lookup in a
Counteradd real overhead, so remove them or put them behind a flag.
Exercise
You predict that the function below performs n * (n + 1) // 2 increments. Instrument-and-test reasoning shows a mismatch at n = 4. What is the actual count, and what is the correct formula? def f(n): steps = 0 for i in range(n): for j in range(i): steps += 1 return steps
Show answer
The inner loop runs i times for i = 0, 1, ..., n-1, so the total is 0 + 1 + ... + (n-1) = n(n-1)/2. At n = 4 the actual count is 6, while the prediction n(n+1)/2 gives 10. The prediction summed 1 through n instead of 0 through n-1. The correct formula is n * (n - 1) // 2.
Exercise
An instrumented function gives counts 3000, 6600, 14400, and 31200 at n = 1000, 2000, 4000, and 8000. Compute the doubling ratios and state the likely order of growth.
Show answer
The ratios are 6600/3000 = 2.2, 14400/6600 ≈ 2.18, and 31200/14400 ≈ 2.17. They sit slightly above 2 and fall slowly, which suggests Θ(n log n). In fact, the counts equal 3n·log2-style terms: 3000 = 3·1000·1 is not the pattern, but 1000·ceil(log2 1000)·0.3 = 3000 is, so the count is roughly 0.3·n·ceil(log2 n). Confirm with an exact derivation before relying on it.
Exercise
You instrument common_items(a, b) with a counter inside the for loop over a, using plain Python integers. It reports len(a) steps, but runtime grows quadratically when both lists double. Explain the discrepancy and give one way to make the counter reveal the real cost.
Show answer
The x in b test on a list is a hidden linear scan of b, and a counter placed in your loop body cannot see it. The real cost is up to len(a) * len(b) comparisons. To expose it, replace x in b with an explicit inner loop over b that increments the counter, or wrap the elements in a class whose _eq increments a counter, using distinct objects so identity checks do not skip eq_.