
Fill in
Prefix Sums
The Guild ledger records lantern oil used each day. Visitors keep asking: "How much oil from day 3 to day 9?" Summing the slice each time is O(n) per question. With prefix sums every question takes O(1) after one O(n) setup.
prefix[i] = total of the first i values (so prefix[0] is 0):
values: [3, 1, 4, 1, 5]
prefix: [0, 3, 4, 8, 9, 14]
The total of values[start:end] is then just
prefix[end] - prefix[start]. For values[1:4] that is 9 - 3 = 6
(that's 1 + 4 + 1). ✔
Pip tip:
itertools.accumulate(values, initial=0)builds the same prefix list in one line.
Assignment
Replace each ___:
build_prefix(values)returns the prefix list (one longer thanvalues).range_total(prefix, start, end)returns the sum ofvalues[start:end](end excluded) using onlyprefix.
Replace each ___:
build_prefix(values)returns the prefix list (one longer thanvalues).range_total(prefix, start, end)returns the sum ofvalues[start:end](end excluded) using onlyprefix.
main.py Python sleeping
Press Run to try your code, then Check to test it.