Boss lesson · Unit 02
A hot loop
Hoist, look up, batch: one slow loop made fast, step by step
What you practise
- Work hoisted out of the loop, repeated lookups removed, built-ins against hand-written loops, batching
- Each change counted
Try a question from this lesson
Pick one
This counts the readings above the average. For 1,000 readings, how many additions does average perform in total during one call of hot?
def average(nums):
total = 0
for n in nums:
total += n
return total / len(nums)
def hot(temps):
count = 0
for t in temps:
if t > average(temps):
count += 1
return countfunction average(nums) {
let total = 0;
for (const n of nums) total += n;
return total / nums.length;
}
function hot(temps) {
let count = 0;
for (const t of temps) {
if (t > average(temps)) count += 1;
}
return count;
}function average(nums: number[]): number {
let total = 0;
for (const n of nums) total += n;
return total / nums.length;
}
function hot(temps: number[]): number {
let count = 0;
for (const t of temps) {
if (t > average(temps)) count += 1;
}
return count;
}Hint
How many times is the averaging function called, and how many additions does each call make?
Correct answer
1,000,000
Why
The loop calls it once per reading, and each call adds up all 1,000 readings: 1,000 × 1,000. Yet the average is the same number every time, because the readings do not change while the loop runs.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Hoisting
A value that comes out the same on every pass of a loop is loop-invariant.
Computing it inside the loop repeats identical work n times. Move it above the loop and compute it once: that is hoisting.
Typical invariants: a total or average of the whole list, a set built from another list, a setting read from a file, a pattern compiled from text.
The test: does this expression mention the loop variable, or anything the loop changes? If not, it can move out.
10 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 4× multiple choice
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.