Sub topic 13
Checking Your Count with a Counter
This chapter assumes you can already derive step counts for single, nested, dependent, and halving loops. You should also know how Big-O and Big-Theta summarize those counts. Here you will test those predictions by running the code.
A derived formula can be wrong in quiet ways: an off-by-one bound, a missed + 1, or a loop you thought was independent but isn't. An instrumented counter catches these mistakes. An instrumented counter is a variable you increment inside the loop body, which records exactly how many times the body ran.
The Verification Loop
Comparing Against an Exact Formula
For the triangular loop from earlier, the prediction is n(n-1)/2. Write the prediction as its own function and compare it with the counter's result across a spread of inputs:
def count_pairs(n):
steps = 0
for i in range(n):
for j in range(i + 1, n):
steps += 1
return steps
def predicted(n):
return n * (n - 1) // 2
for n in (0, 1, 2, 5, 10, 100):
measured = count_pairs(n)
expected = predicted(n)
status = "ok" if measured == expected else "MISMATCH"
print(f"n={n:4d} measured={measured:6d} predicted={expected:6d} {status}")Every row prints ok, ending with measured= 4950 predicted= 4950. Include the small cases 0, 1, and 2. Off-by-one errors usually show up there first, and a formula that only holds for large n is probably an approximation, not the exact count.
Checking Growth When There Is No Clean Formula
Sometimes you only want to confirm the order of growth. A doubling test works for this. Measure the count at n and at 2n, then look at the ratio:
| Growth | Ratio count(2n) / count(n) |
|---|---|
| Θ(log n) | close to 1, and it falls as n grows |
| Θ(n) | 2 |
| Θ(n log n) | slightly above 2 |
| Θ(n²) | 4 |
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):
k = n
while k > 0:
k //= 2
steps += 1
return steps
for n in (1000, 2000, 4000, 8000):
r1 = count_n_log_n(2 * n) / count_n_log_n(n)
r2 = count_pairs(2 * n) / count_pairs(n)
print(f"n={n:5d} n log n ratio={r1:.2f} pairs ratio={r2:.2f}")The n log n ratios come out as 2.20, 2.18, 2.17, and 2.15. They drift down toward 2 because log(2n)/log n approaches 1. The pairs ratio stays at 4.00, which confirms quadratic growth.
Common Errors
- Counter in the wrong place. If you put
steps += 1in the outer loop of a nested pair, you count outer iterations only. Put the counter in the body whose executions you are predicting. - Testing only one input. One matching value can be a coincidence. Test at least one small case, one edge case, and one larger case.
- Trusting the counter over hidden work. The counter adds one per iteration, even when that iteration does an
x in some_listscan. The counter confirms your loop structure. It does not see the cost of loops inside built-in operations. - Confusing counts with time. A counter measures steps, which is deterministic. Wall-clock timing is noisy and depends on the machine, which is why step counts are the better tool for checking an analysis.
Exercise
You predict that for i in range(1, n, 2): runs ceil((n - 1) / 2) times. Your counter reports 50 for n = 100 and 50 for n = 101. Does the prediction hold for both inputs?
Show answer
Yes. For n = 100, ceil(99 / 2) = ceil(49.5) = 50. For n = 101, ceil(100 / 2) = 50. Both ranges visit 1, 3, ..., 99, which is 50 values.
Exercise
A student instruments count_pairs but places steps += 1 directly under for i in range(n):, before the inner loop. The counter returns 10 for n = 10, not 45. What did they measure, and how should they fix it?
Show answer
They counted outer-loop iterations, which is n. To count inner-body executions, move steps += 1 inside the for j in range(i + 1, n): loop. The counter then returns n(n-1)/2 = 45.
Exercise
A doubling test gives ratios of 1.10, 1.09, and 1.08 for n = 1000, 2000, and 4000. Which growth class does this suggest?
Show answer
Θ(log n). The ratios are near 1 and still falling, which matches log(2n)/log n. A linear function would give 2, and n log n would give slightly more than 2.