Correctness and Efficiency

The program below is correct. It prints how far each of today's eight hourly readings from one air-quality sensor lies from yesterday's average. This lesson counts the work it does, finds where it does more than it needs to, and then searches today's readings once they're sorted.
readings = [41, 38, 52, 47, 35, 44, 50, 45]
yesterday = [40, 36, 49, 45, 33, 42, 47, 44]
def average(values):
    return sum(values) / len(values)
gaps = []
for reading in readings:
    gaps.append(abs(reading - average(yesterday)))
print(gaps)
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.

Yesterday's readings average 42.0, and the program prints
[1.0, 4.0, 10.0, 5.0, 7.0, 2.0, 8.0, 3.0]
Run the program above to see that list. When the lesson stores the average before the loop, make the same change in the program and run it again.

Counting the work

For today's eight readings, the loop body runs 8 times. Each pass calls average(yesterday), and its sum reads all eight of yesterday's readings. Thus sum reads a reading 8 × 8 = 64 times, and all eight calls return the same 42.0.
Reads made by sum inside average(yesterday). Columns: yesterday's values, read by the call: 40, 36, 49, 45, 33, 42, 47, 44. Rows: pass 1 (reading 41), pass 2 (reading 38), pass 3 (reading 52), pass 4 (reading 47), pass 5 (reading 35), pass 6 (reading 44), pass 7 (reading 50), pass 8 (reading 45), each with all eight cells filled. Call inside the loop: 8 passes × 8 reads = 64 reads. Once, before the loop: one row of eight cells. Call stored before the loop: 8 reads, same printed list.

One call before the loop

The loop appends to gaps and doesn't change yesterday, so every call returns 42.0. We call average once, before the loop, and store its answer.
readings = [41, 38, 52, 47, 35, 44, 50, 45]
yesterday = [40, 36, 49, 45, 33, 42, 47, 44]
def average(values):
return sum(values) / len(values)
avg = average(yesterday)
gaps = []
for reading in readings:
gaps.append(abs(reading - avg))
print(gaps)
It prints the same list. Now sum reads yesterday's 8 readings once, and the loop still runs 8 times.
The first program never breaks that condition. A second loop over the same readings does: it compares each reading with the average of the readings so far.
seen = []
for reading in readings:
seen.append(reading)
print(abs(reading - average(seen)))
Since seen grows on every pass, average(seen) returns 41.0 on the first pass and 44.0 only on the last. One call before the loop would run on an empty seen, and Python would stop with ZeroDivisionError.
The program below has that shape on a runner's lap times, in seconds: each pass compares a lap with the average of the laps so far. Run it, then change it and run it again:
• Add a fifth lap time to the list.
• Add avg = average(seen) on the line above the for, and change average(seen) in the print line to avg.
def average(values):
    return sum(values) / len(values)

laps = [60, 64, 59, 65]
seen = []
for lap in laps:
    seen.append(lap)
    print(lap, "seconds, average so far:", average(seen))
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.

Constant time

With avg stored, the newest reading's gap, abs(readings[-1] - avg), is 3.0. Computing it reads one reading, whether the list holds 8 readings or 64.

Searching the sorted readings

Sorting the readings with ordered = sorted(readings) gives [35, 38, 41, 44, 45, 47, 50, 52]. A binary search for 48 starts with all 8 as candidates. Each probe reads the middle candidate and keeps the side where 48 would have to be.
ProbeCandidatesMiddle reading
1indices 0 to 744, at index 3
2indices 4 to 747, at index 5
3indices 6 to 750, at index 6
Binary search for 48 in the sorted readings 35, 38, 41, 44, 45, 47, 50, 52, at indices 0 to 7. Probe 1: middle of 0 to 7 is index 3, holding 44; 48 is greater than 44, keep indices 4 to 7. Probe 2: middle of 4 to 7 is index 5, holding 47; 48 is greater than 47, keep indices 6 to 7. Probe 3: middle of 6 to 7 is index 6, holding 50; 48 is less than 50, no indices left: 48 is not in the list. Gray, crossed out: eliminated before this probe.
The third probe leaves no candidate, since 48 is larger than 47 and smaller than 50, so the search reports that 48 isn't there. Three halvings take 8 candidates to 1, so no search of these readings needs more than four probes: one per halving, plus one to check the last candidate. A sorted log of 64 readings halves six times: 32, 16, 8, 4, 2, and 1. A binary search of it needs at most 7 probes, and a sequential search can read all 64.
Each probe discards a half by assuming that order, and nothing in the search tests it. Run on today's unsorted readings, the check fails at the first pair, since 41 is larger than 38.

Reasonable and unreasonable time

If each day held 64 readings, the first program's calls to average would read a reading 64 × 64 = 4,096 times, the square of the length. The improved program reads each of yesterday's readings once in sum and each of today's once in the loop.
Both counts are polynomials in the length, so both programs run in reasonable time. A program that tries every group of readings, looking for one that adds to exactly 500, is exponential. Each reading is either in a group or out of it, so 64 readings form 2 ** 64 groups, and each added reading doubles the count. At a billion groups a second, trying them all would take about 585 years.