Skip to content
Tactiverge

School/○ Innovator/Week 6

Count the steps before you time them

Checking every pair of 1,000 waypoints for collisions: is that 1,000 checks, 500,000, or a million?

About 35 min · 3 goals · Checked by automated tests

1.Why should I care?

Before you measure a program you can often predict its cost by counting: how many times does the innermost line run? That count, as a formula in n, tells you whether your planner will cope with a 10× bigger map, before you build the map.

  • ◇ Count how many times a loop body runs for single, nested and dependent loops.
  • ◇ Use the sum 0 + 1 + … + (n − 1) = n(n − 1)/2 for triangular loops.
  • ◇ Predict how the count changes when the input size doubles.

2.Predict

count = sum(1 for i in range(n) for j in range(i)) checks each pair of n waypoints once. For n = 1,000, what is count?

Guess first. Being wrong here is how the surprise works.

3.Discover

Turn on only n and n² and slide n from 2 to 1,000. Read the 'when n doubles' column. Then add n log n and log n. Which growth would your collision check (all pairs) follow?

Loading the interactive…

Can't use the interactive? Read a description instead

The plotter draws operation counts against n for log n, n, n log n and n², and a table gives each count and the factor it grows by when n doubles: about 1 extra step for log n, 2 for n, a little over 2 for n log n and 4 for n².

4.Checkpoint: guided practice

Check what you just discovered before going on. Hints appear after a wrong answer.

Practice 1 · a fresh version every time

A program is comparing every pair of waypoints. Its step count is measured with: count = sum(1 for i in range(0, 266, 10)). What value does count hold?

steps

Practice 2 · a fresh version every time

A program is filling a cost table for a route planner. Its step count is measured with: count = sum(1 for i in range(10) for j in range(6)). What value does count hold?

steps

5.Understand

Single and nested loops

A loop over range(n) runs n times. A loop inside a loop multiplies: range(a) around range(b) runs a × b times. Three nested loops over n run n³ times. Loops one after another add: n + n = 2n.

When the inner loop depends on the outer

If the inner range uses i, add up the inner counts. range(i) gives 0 + 1 + … + (n − 1) = n(n − 1)/2; range(i, n) gives n + (n − 1) + … + 1 = n(n + 1)/2. A step, range(0, n, k), runs ⌈n/k⌉ times.

Count the expensive line

You don't need to count every statement. Pick the line that runs most often (a comparison, a distance calculation) and count that. Its formula dominates the program's cost as n grows.

Explain it another way

Shaking hands with everyone in a room of n people: each new person shakes hands with all who arrived before. That's the triangular count, about half of n².

Derivation: Why the triangular loop costs n(n − 1)/2
  1. The loop for i in range(n): for j in range(i): runs the inner body i times on pass i, for i = 0, 1, …, n − 1.

  2. Total S = 0 + 1 + 2 + … + (n − 1).

  3. Write the sum forwards and backwards and add: each column gives (n − 1), and there are n columns, so 2S = n(n − 1).

  4. Therefore S = n(n − 1)/2. For n = 1000: 1000 × 999 / 2 = 499,500.

  5. For large n this is about n²/2: still quadratic. Doubling n multiplies it by about 4.

Worked example 1

Count the pair checks for n waypoints and confirm with the formula.

def pair_checks(n):
    count = 0
    for i in range(n):
        for j in range(i):        # each pair (j, i) with j < i, once
            count += 1
    return count


for n in [4, 10, 1000]:
    print(n, pair_checks(n), n * (n - 1) // 2)
# 4 6 6
# 10 45 45
# 1000 499500 499500

Common mix-ups

  • Two nested loops always cost n².
    ✓ Only if both run n times. A dependent inner loop can give n(n − 1)/2, and a fixed inner loop of 4 neighbours gives 4n.
  • Counting operations is pointless when computers are fast.
    ✓ Fast computers make large n affordable, which is exactly when quadratic counts explode.

6.Practice on your own

Practice, not a test. Wrong answers get a hint and another try.

Practice 3 · a fresh version every time

A program is scanning a sensor log. Its step count is measured with: count = sum(1 for i in range(36) for j in range(i)). What value does count hold?

steps

Practice 4

pair_checks(1000) is 499,500. About how big is pair_checks(2000)?

Practice 5

One loop over n readings filters spikes; a second loop over n readings averages them. How many loop passes in total?

7.Apply it

For your BFS planner, count how many times the neighbour check runs on an open n × n grid (each cell is expanded once and checks 4 neighbours). Write the formula, then check it by adding a counter to your code for n = 10, 20 and 40.

8.Reflect

Concepts: Algorithms, searching and complexity