Counting the steps
Counting the steps means adding a counter to see how many times the basic operation runs as the data size n grows, which unlike a stopwatch gives the same answer on every machine: finding the maximum takes n − 1 comparisons.
You need to check 10,000 order numbers for duplicates. A colleague writes two nested loops, you write one. Time each with a stopwatch: this run yours is 0.3 seconds faster, the next only 0.1, and on the server it is another number again. A stopwatch measures this machine at this moment, and it changes as soon as something else runs in the background. When an algorithms course compares speed it compares something that does not change: how fast the number of steps grows as the data grows. Two nested loops over 10,000 numbers make about 50 million comparisons, one loop makes 10,000: that gap is the same on every machine.
Why a stopwatch misleads
Run the same program on the same data three times and the stopwatch gives three different numbers; move to another computer and they differ several times over. But how many comparisons the program made is the same every time, because it depends only on the code and the data.
| Run | Stopwatch | Comparisons |
|---|---|---|
| Laptop, run 1 | about 0.61 s | 9 999 999 |
| Laptop, run 2 | about 0.74 s | 9 999 999 |
| Server | about 0.18 s | 9 999 999 |
So in this course speed is always counted with a counter: next to the operation done most often, write steps += 1, and print steps at the end. One comparison, one assignment, one addition: each is a step. A step count has nothing to do with the machine, it is the same on every run, and you can compare it.
Lin's program took 3 seconds on his computer; Zhou's took 1 second on hers. Can you say Zhou's algorithm is faster?
Which step to count: the basic operation
A program does assignments, comparisons, additions… Counting every kind would be tedious. Usually you count just one: the statement that runs most often, called the basic operation. It is normally in the innermost loop; everything else runs about as often, or far less.
Take the plainest possible sum loop over n numbers and count every line:
total = 0①for x in nums②: total += x③print(total)④
- ①once
- ②n times: takes one number each time, stops when they run out
- ③n times: this is the basic operation
- ④once
All together that is about 1 + n + n + 1 = 2n + 2. What decides the speed is the n runs of total += x: make n ten times bigger and the total grows about ten times too. So in practice you count only the basic operation and say "this code takes about n steps".
With a while loop, watch out for the "one extra": the condition i < n is checked once per pass through the loop, and then one more time, when it turns false and the loop ends.
With n = 10, how many times is the condition i < n checked?
1n = 102i = 03while i < n:4 i += 1
Counting: finding the maximum
To find the largest of n numbers, take the first as "the largest so far" and compare the rest with it one by one.
i1best = nums[0]2for i in range(1, len(nums)):3 steps += 14 if nums[i] > best:5 best = nums[i]
Put the counter inside the function and try a few different n:
1def find_max(nums):2 steps = 03 best = nums[0]4 for i in range(1, len(nums)):5 steps += 1 # one comparison6 if nums[i] > best:7 best = nums[i]8 return best, steps9 10data = [(i * 37) % 101 for i in range(10000)]11for n in [10, 100, 1000, 10000]:12 best, steps = find_max(data[:n])13 print(f"n = {n:5} max {best:3} {steps:4} comparisons")
n = 10 max 94 9 comparisons n = 100 max 100 99 comparisons n = 1000 max 100 999 comparisons n = 10000 max 100 9999 comparisons
Make n 10 times bigger and the comparisons become about 10 times as many: the step count grows with n, it is n − 1. You get that number on any computer.
Finding the maximum of 50 numbers, with steps counting comparisons. What does it print?
1nums = [i % 7 for i in range(50)]2steps = 03best = nums[0]4for i in range(1, len(nums)):5 steps += 16 if nums[i] > best:7 best = nums[i]8print(best, steps)
Change only the number in the green box so that the program prints 99.
1n = 2steps = 03for i in range(1, n):4 steps += 15print(steps)
99
Two nested loops
The most common use of two nested loops is comparing every pair once. For example, checking a list for duplicates:
i↑j1for i in range(len(nums)):2 for j in range(i + 1, len(nums)):3 if nums[i] == nums[j]:4 return True5return False
The worst case is no duplicate at all: every pair has to be compared before you can say "none". Count them:
1def has_dup(nums):2 steps = 03 for i in range(len(nums)):4 for j in range(i + 1, len(nums)):5 steps += 16 if nums[i] == nums[j]:7 return True, steps8 return False, steps9 10for n in [10, 100, 500]:11 found, steps = has_dup(list(range(n)))12 print(f"n = {n:3} duplicate: {found} {steps} comparisons")
n = 10 duplicate: False 45 comparisons n = 100 duplicate: False 4950 comparisons n = 500 duplicate: False 124750 comparisons
n goes from 10 to 100 (10 times), the comparisons go from 45 to 4950 (110 times). For every step of the outer loop the inner loop walks the rest of the list, so the count grows much faster than n.
The inner loop starts at i (not i + 1). What does it print for n = 10?
1n = 102steps = 03for i in range(n):4 for j in range(i, n):5 steps += 16print(steps)
You check 10 numbers for duplicates by comparing every pair once. With no duplicates at all, how many comparisons does that take?
Everyone shakes hands once
✓n people, and every two of them shake hands once (once for every pair with i < j). Finish the two loops and count the handshakes for n = 5 and n = 6.
10 15
1def handshakes(n):2 steps = 03 for i in range(n):4 pass # another loop inside: j starts at i + 1, add 1 to steps for each pair5 return steps6 7print(handshakes(5))8print(handshakes(6))
Counting other kinds of loop
Not every loop runs exactly n times. Before counting, check three things: where it starts, where it stops, and how much it changes each time. Here they are side by side for n = 64:
for i in range(n)64 timesn timesfor i in range(0, n, 2)32 timesn / 2 times: still grows with nwhile i < n: i *= 26 timesgrows very slowly: the log n of lesson 3- Up by 2:
range(0, n, 2)covers only half, n / 2 times. Make n ten times bigger and so is the count: it grows just like a single pass. - Times 2: 1, 2, 4, 8… passes n in a few steps. For n = 64 that is 6 passes; for a million, only 20.
- A fixed inner loop:
for j in range(3)runs 3 times however big n is, so inside an outer loop of n it adds up to 3n. Two nested loops are not always n²: it depends on whether the inner one grows with n.
range steps by 3. What does it print?
1n = 302steps = 03for i in range(0, n, 3):4 steps += 15print(steps)
The inner loop always runs 4 times. What does it print?
1n = 1002steps = 03for i in range(n):4 for j in range(4):5 steps += 16print(steps)
Doubling each time
✓i starts at 1 and is doubled each time, until it is no longer less than n. Finish the loop and count how many doublings it takes for n = 64 and n = 1000.
6 10
1def doublings(n):2 steps = 03 i = 14 # while i < n: double i, add 1 to steps5 return steps6 7print(doublings(64))8print(doublings(1000))
Keep only the fastest-growing term
Write the steps as a formula in n: finding the maximum is n − 1, checking for duplicates is n(n − 1)/2, that is n²/2 − n/2. Real code has a few extra odd steps too, say 3n + 2. While n is small these extras matter a little; once n is large, the fastest-growing term buries everything else:
| n | 3n + 2 | n²/2 | Time for 3n + 2 | Time for n²/2 |
|---|---|---|---|---|
| 10 | 32 | 50 | instant | instant |
| 1 000 | 3 002 | 500 000 | instant | about 0.05 s |
| 1 000 000 | 3 000 002 | 500 000 000 000 | about 0.3 s | about 14 hours |
("Time" is a rough estimate at about 10⁷ Python steps a second: a Python step is slower than a C one, but the ratios stay exactly the same.)
At a million numbers, n²/2 is over a hundred thousand times 3n + 2. The coefficient in front (3 or 1/2) and the odd bits at the end (+ 2) do not matter next to a gap like that. So when you compare algorithms, keep only the fastest-growing term. The next lesson writes this down as "big O".
In interviews: asked "how fast is this code?", do not say "I ran it, 0.2 seconds". Say "the outer loop runs n times, the inner one at most n times, so about n²/2 comparisons", then give the big O.
The step count is 2n² + 30n + 500. When n is large, which term decides the speed?
How you write it at work
There is no library for counting steps; a counter of your own is the most direct way. To count several kinds of operations at once (comparisons, swaps, reads and writes), use collections.Counter: a key it has not seen counts as 0, so ops["swaps"] += 1 needs no setting up first.
1from collections import Counter2 3def one_pass(nums, ops):4 # one pass of bubble sort: compare neighbours, swap if the first is bigger5 for i in range(len(nums) - 1):6 ops["comparisons"] += 17 if nums[i] > nums[i + 1]:8 nums[i], nums[i + 1] = nums[i + 1], nums[i]9 ops["swaps"] += 110 11ops = Counter()12nums = [5, 1, 4, 2, 8]13one_pass(nums, ops)14print(nums)15print(ops["comparisons"], "comparisons,", ops["swaps"], "swaps")
[1, 4, 2, 5, 8] 4 comparisons, 3 swaps
A few everyday rules:
- To see which of two ways of writing it is faster (how the algorithm grows): count with a counter, or count the loops just by reading the code (next lesson).
- To find where a live program is slow: that is another job. Measure on real data with tools like
cProfileortimeit, several times, and take the average. They answer "how many seconds on this machine", not "how fast does it grow". - Add counters only while analysing and remove them afterwards:
steps += 1takes time too.
A Counter counts comparisons and swaps at the same time during one pass over [3, 2, 1]. What does it print?
1from collections import Counter2 3ops = Counter()4nums = [3, 2, 1]5for i in range(len(nums) - 1):6 ops["cmp"] += 17 if nums[i] > nums[i + 1]:8 nums[i], nums[i + 1] = nums[i + 1], nums[i]9 ops["swap"] += 110print(nums, ops["cmp"], ops["swap"])
Summary
Comparing speed: count the steps, see how they grow with n
- A stopwatch changes every run; a step count depends only on code and data
- Write steps += 1 next to the most frequent operation and print it at the end
- One pass: about n steps; every pair once: about n²/2 steps
- When n is large, keep only the fastest-growing term
- Stepping by 2 is still about n steps, doubling takes only log n; a fixed inner loop is not n²
1steps = 02for i in range(n):3 for j in range(i + 1, n):4 steps += 1 # about n²/2 times5print(steps)