How Late Do the Books Come Back?

Data with PythonMedium+20 XP+20

How Late Do the Books Come Back?

A town's library service logs returned books by branch and by how late they came back. Each month's export is a list of (branch, band, count) records, and several months have been stacked together, so the same branch and band can turn up in more than one record.

The lateness bands have a natural order, best first, for example:

For each branch, the manager wants a running share: the percentage of that branch's returns that came back no later than each band. For a branch with 10 returns (6 on time, 3 that were 1–3 days late, none 4–7 days late and 1 that was 8+ days late) that is

1[60.0, 90.0, 90.0, 100.0]

since 6/10=60%6/10 = 60\%6/10=60% were on time, (6+3)/10=90%(6+3)/10 = 90\%(6+3)/10=90% were at most 3 days late, still 90%90\%90% were at most 7 days late, and by the last band every book is counted.

Task: write running_shares(records, bands) in plain Python (no pandas needed).

  • records is a list of (branch, band, count) tuples, in no particular order. Counts for the same branch and band add up.
  • bands lists every band, best first. Every record's band is in it. A band with no returns at a branch counts as 0 there.
  • Each branch's percentages are out of that branch's own total, which is always more than 0.
  • Return a list of (branch, shares) tuples, one per branch that appears in records, sorted alphabetically by branch. shares holds one percentage per band, in the order of bands, each a float rounded to 4 decimal places.

Examples

records = [("Hillside", "on time", 30), ("Hillside", "1-3 days late", 12), ("Hillside", "4-7 days late", 5), ("Hillside", "8+ days late", 3), ("Quayside", "on time", 18), ("Quayside", "1-3 days late", 9), ("Quayside", "4-7 days late", 2), ("Quayside", "8+ days late", 1)]
bands = ["on time", "1-3 days late", "4-7 days late", "8+ days late"]
returns [('Hillside', [60.0, 84.0, 94.0, 100.0]), ('Quayside', [60.0, 90.0, 96.6667, 100.0])]
records = [("Oakfield", "on time", 7), ("Oakfield", "4-7 days late", 4), ("Elmbridge", "8+ days late", 2), ("Elmbridge", "on time", 3), ("Oakfield", "on time", 3), ("Elmbridge", "1-3 days late", 4)]
bands = ["on time", "1-3 days late", "4-7 days late", "8+ days late"]
returns [('Elmbridge', [33.3333, 77.7778, 77.7778, 100.0]), ('Oakfield', [71.4286, 71.4286, 100.0, 100.0])]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run