python · level 3 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Best case, worst case. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def find(target, items):
checks = 0
for item in items:
checks = checks + 1
if item == target:
break
return checks
names = ["Ana", "Ben", "Cara", "Dev", "Eli"]
print(find("Ana", names), find("Eli", names), find("Zed", names))
your turn
Your turn. Count the work in a repeat finder.
Put five or six different numbers in the list, separated by commas, and run it. Then add a repeat of the first one and run again.
fix it
Ten items compared with ten should be 100 steps.
- The inner loop runs 10 times for every outer step. How often does the comparison run in total?
- The counter sits in the outer loop, so it only counts outer steps.
- Indent
steps = steps + 1so it lines up withsame = a == b, then run.
nailed it
you can measure work without a stopwatch. :D
- Count how often the busiest line runs.
- Searching a list checks item after item.
- A loop inside a loop multiplies the steps.
new words in your collection
- cost
- nested loop
This lesson isn’t saved. A free account remembers every lesson you finish.