×

python · level 3 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Count the steps to see how much work your code does.

Fast code is mostly code that does less work. To judge it, count steps rather than seconds: how many times does the busiest line run? That count is the of the code.

Looping over a list of 1,000 items costs 1,000 steps. x in a_list costs the same, because Python checks item after item until it finds a match.

A multiplies: 1,000 outer steps, each running 1,000 inner steps, makes a million. Double the data and the work grows four times. That is the line to rewrite first.

def count_pairs(items):
    steps = 0
    for a in items:
        for b in items:
            steps = steps + 1
    return steps

for size in [10, 100, 1000]:
    print(size, "items:", count_pairs(range(size)), "steps")

Seconds change from computer to computer, but the number of steps stays the same.