17. Algorithms and data structures — Mini-project
The maintenance team of a factory monitors four machines with sensors S1 to S4. Every morning, they ask the same questions about the last two weeks of logs: How long did each machine run without a warning? What were the worst vibration readings? When did the vibration of S4 first reach the fail level? What happened during a given night shift? A first script answered these questions with nested loops and full scans. It worked, but the team wants to ask hundreds of time-range questions from a dashboard, and the scans are too slow.
Write a script, sensor_queries.py, that answers every question with the algorithm that fits it, and that proves its speed by counting comparisons. It runs with one command, python sensor_queries.py, from your project folder.
The project uses the core patterns of module 17: sorted data and binary search with bisect, a hand-written binary search with a counter, a heap for the top k, a monotonic deque for a rolling maximum, a one-pass streak (a variable-size window), and hash maps for grouping.
Dataset
Section titled “Dataset”data/sensors.csv has 8,064 rows: 4 sensors × 2,016 readings, one every 10 minutes from 2024-05-01 00:00 to 2024-05-14 23:50. The file is sorted by timestamp, then sensor_id.
| Column | Type | Notes |
|---|---|---|
timestamp |
text, ISO YYYY-MM-DDTHH:MM:SS |
sorts as text in time order |
sensor_id |
text | S1 … S4 |
temperature_c |
float | 22 blank cells |
humidity_pct |
float | not used in this project |
vibration_mm_s |
float | 30 blank cells |
status |
text | ok, warn or fail; never blank |
The status rule of the dataset is fail when vibration ≥ 11.2 mm/s or temperature ≥ 42 °C, and warn when vibration ≥ 4.5 mm/s or temperature ≥ 33 °C. Sensor S4 wears out from May 12, so its vibration rises at the end of the period.
Requirements
Section titled “Requirements”Your script must:
- Load the file once into a dict that maps each sensor id to its list of readings, sorted by timestamp. Store blank cells as
None, not as 0. - Answer a time-range question (
start <= timestamp < end) with two binary searches (bisect_leftwithkey=), not with a scan. - Find the longest run of consecutive
okreadings of each sensor in one pass. - Find the 3 highest vibration readings of S4 with
heapq.nlargest, skipping blanks. - Compute the rolling 1-hour (6-reading) maximum of S4 vibration with a monotonic deque in . Report the number of windows at fail level and the end of the first one.
- Report the number of readings and the mean vibration of S4 in the night shift of 2024-05-13, 00:00 to 06:00.
- Generate 500 random time ranges with
random.Random(42). Count the comparisons of a linear scan and of a hand-written binary search for all of them, check that both give the same counts, and print both totals. - Use type hints on every function and a docstring on every non-trivial one.
- Print the report below exactly.
The expected report:
Sensor log report=================S1: 2016 readings, longest ok run 625 (2024-05-07T13:50 to 2024-05-11T21:50)S2: 2016 readings, longest ok run 307 (2024-05-07T16:50 to 2024-05-09T19:50)S3: 2016 readings, longest ok run 490 (2024-05-11T13:20 to 2024-05-14T22:50)S4: 2016 readings, longest ok run 199 (2024-05-08T02:20 to 2024-05-09T11:20)
Top 3 vibration readings of S4: 2024-05-12T06:40:00 18.98 mm/s fail 2024-05-13T01:30:00 18.57 mm/s fail 2024-05-04T10:30:00 17.73 mm/s fail
Rolling 1-hour max of S4 vibration: 2004 windows at fail level (>= 11.2 mm/s): 90 first one ends at 2024-05-01T08:00:00
S4 on 2024-05-13 00:00-06:00: 36 readings, mean vibration 6.47 mm/s
500 range queries: linear 1,008,000 comparisons, binary 10,978 (at most 22 per query)Step plan
Section titled “Step plan”-
Load. Read the CSV with
csv.DictReader. Append each row as a tuple(timestamp, temperature, vibration, status)toseries[sensor_id], adefaultdict(list). Convert blank cells with a helperto_float(text)that returnsNonefor"". Sort each list by timestamp: the file is already sorted, so Timsort needs only one pass. -
Range query. Write
between(readings, start, end).bisect_left(readings, start, key=lambda r: r[0])finds the first reading at or afterstart; the same call withendfinds the first reading at or afterend. Return the slice between them. -
Streaks. Write
longest_run(readings, status). Keep the index where the current run started, reset it when the status changes, and remember the best length with its first and last timestamps. -
Top k. Write
top_vibration(readings, k)withheapq.nlargest(k, ..., key=...)over the readings whose vibration is notNone. -
Rolling maximum. Write
rolling_max(values, k)with a deque of indices whose values decrease from front to back. Test it on a short list against[max(values[i:i + k]) ...]. -
Night shift. Use
between()for 2024-05-13 00:00 to 06:00 and average the vibrations that are notNone. -
Prove the speed. Write
lower_bound(times, target, counter)(the lesson’s binary search with a counter) andcount_linear(times, start, end, counter). For each of the 500 random ranges, the binary count islower_bound(times, end) - lower_bound(times, start).assertthat it equals the linear count. -
Report. Put the calls in
main()behindif __name__ == "__main__":and print the report. Compare every line with the expected report.
A skeleton to start from:
"""sensor_queries.py: fast answers to maintenance questions about sensor logs."""
import csvimport heapqimport mathimport randomfrom bisect import bisect_leftfrom collections import defaultdict, deque
Reading = tuple[str, float | None, float | None, str]
def load_series(path: str) -> dict[str, list[Reading]]: ... # TODO: one list of readings per sensor, sorted by timestamp
def between(readings: list[Reading], start: str, end: str) -> list[Reading]: ... # TODO: two bisect_left calls with key=
def longest_run(readings: list[Reading], status: str) -> tuple[int, str, str]: ... # TODO: one pass; return (length, first timestamp, last timestamp)
def top_vibration(readings: list[Reading], k: int) -> list[Reading]: ... # TODO: heapq.nlargest, skipping None
def rolling_max(values: list[float], k: int) -> list[float]: ... # TODO: monotonic deque of indices
def main() -> None: ... # TODO: print the report
if __name__ == "__main__": main()Rubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Runs as a script | 2 | python sensor_queries.py runs with no error and prints the report |
| Correct numbers | 3 | Every line matches the expected report |
| Loading | 2 | One pass over the file; blanks are None; each sensor’s list is sorted |
| Range queries | 3 | between() and the counted version use binary search, not a scan |
| Top k and rolling max | 3 | heapq.nlargest for the top 3; a monotonic deque gives the rolling maximum in |
| Streaks | 2 | One pass with a reset, not a nested loop |
| Proof of speed | 2 | Both comparison totals are printed, and an assert shows the two methods agree |
| Code quality | 2 | Type hints, docstrings, a main() with a main guard, ruff-clean |
| Total | 19 | 15 or more: you are ready for the Part 2 checkpoint |
Stretch goals
Section titled “Stretch goals”- Add
longest_stable(values, tol)from exercise M17-X03 and report the longest stretch in which the temperature of each sensor stayed within 0.5 °C. - Turn the rolling alerts into incidents (exercise M17-X02) and print one line per incident of S4.
- Add an
argparsecommand line (module 08):python sensor_queries.py --sensor S2 --from 2024-05-03T00:00:00 --to 2024-05-04T00:00:00prints the readings in that range. - Replace the 500 random queries with a sorted batch of queries and answer all of them in one merge-style pass with two pointers. Count the comparisons. When does this beat 500 separate binary searches?
- Write pytest tests (module 14) for
between,longest_runandrolling_max, including empty input and a range outside the data.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names and structure can differ; your report must not.
Reference solution
"""sensor_queries.py: fast answers to maintenance questions about sensor logs.
Each query uses the structure that fits it: bisect for time ranges, a heap forthe top k, a monotonic deque for a rolling maximum and one pass for streaks."""
import csvimport heapqimport mathimport randomfrom bisect import bisect_leftfrom collections import defaultdict, deque
# (timestamp, temperature_c, vibration_mm_s, status); blank cells become NoneReading = tuple[str, float | None, float | None, str]FAIL_VIBRATION = 11.2 # mm/s, the fail rule of the datasetWINDOW = 6 # readings: one hour at one reading per 10 minutes
def to_float(text: str) -> float | None: return float(text) if text else None
def load_series(path: str) -> dict[str, list[Reading]]: """Return the readings of each sensor, sorted by timestamp.""" series: dict[str, list[Reading]] = defaultdict(list) with open(path, newline="", encoding="utf-8") as f: for row in csv.DictReader(f): series[row["sensor_id"]].append( ( row["timestamp"], to_float(row["temperature_c"]), to_float(row["vibration_mm_s"]), row["status"], ) ) for readings in series.values(): readings.sort(key=lambda r: r[0]) # one run if the file is sorted: O(n) return dict(series)
def lower_bound(times: list[str], target: str, counter: list[int]) -> int: """First index with times[i] >= target; counter[0] counts comparisons.""" lo, hi = 0, len(times) while lo < hi: mid = (lo + hi) // 2 counter[0] += 1 if times[mid] < target: lo = mid + 1 else: hi = mid return lo
def between(readings: list[Reading], start: str, end: str) -> list[Reading]: """Readings with start <= timestamp < end, found with two binary searches.""" i = bisect_left(readings, start, key=lambda r: r[0]) j = bisect_left(readings, end, key=lambda r: r[0]) return readings[i:j]
def count_linear(times: list[str], start: str, end: str, counter: list[int]) -> int: """The same count with a full scan; counter[0] counts comparisons.""" total = 0 for t in times: counter[0] += 1 if start <= t < end: total += 1 return total
def top_vibration(readings: list[Reading], k: int) -> list[Reading]: """The k readings with the highest vibration, highest first.""" valid = (r for r in readings if r[2] is not None) return heapq.nlargest(k, valid, key=lambda r: r[2])
def rolling_max(values: list[float], k: int) -> list[float]: """Maximum of every window of k values, with a monotonic deque: O(n).""" window: deque[int] = deque() maxima: list[float] = [] for i, value in enumerate(values): while window and values[window[-1]] <= value: window.pop() window.append(i) if window[0] <= i - k: window.popleft() if i >= k - 1: maxima.append(values[window[0]]) return maxima
def longest_run(readings: list[Reading], status: str) -> tuple[int, str, str]: """Longest run of consecutive readings with this status: (length, first, last).""" best = (0, "", "") run_start = None for i, r in enumerate(readings): if r[3] != status: run_start = None continue if run_start is None: run_start = i length = i - run_start + 1 if length > best[0]: best = (length, readings[run_start][0], r[0]) return best
def main() -> None: """Load the log, run every query and print the report.""" series = load_series("data/sensors.csv") print("Sensor log report") print("=================") for sensor_id, readings in sorted(series.items()): length, first, last = longest_run(readings, "ok") print( f"{sensor_id}: {len(readings)} readings, longest ok run {length}" f" ({first[:16]} to {last[:16]})" )
s4 = series["S4"] print("\nTop 3 vibration readings of S4:") for ts, _, vibration, status in top_vibration(s4, 3): print(f" {ts} {vibration:5.2f} mm/s {status}")
valid = [(r[0], r[2]) for r in s4 if r[2] is not None] maxima = rolling_max([v for _, v in valid], WINDOW) first_fail = next(i for i, m in enumerate(maxima) if m >= FAIL_VIBRATION) fail_windows = sum(1 for m in maxima if m >= FAIL_VIBRATION) print(f"\nRolling 1-hour max of S4 vibration: {len(maxima)} windows") print(f" at fail level (>= {FAIL_VIBRATION} mm/s): {fail_windows}") print(f" first one ends at {valid[first_fail + WINDOW - 1][0]}")
night = between(s4, "2024-05-13T00:00:00", "2024-05-13T06:00:00") vib = [r[2] for r in night if r[2] is not None] print(f"\nS4 on 2024-05-13 00:00-06:00: {len(night)} readings, mean vibration" f" {sum(vib) / len(vib):.2f} mm/s")
times = [r[0] for r in s4] rng = random.Random(42) queries = [] for _ in range(500): a, b = sorted(rng.sample(times, 2)) queries.append((a, b)) linear, binary = [0], [0] for a, b in queries: fast = lower_bound(times, b, binary) - lower_bound(times, a, binary) assert fast == count_linear(times, a, b, linear) bound = 2 * math.ceil(math.log2(len(times) + 1)) print(f"\n500 range queries: linear {linear[0]:,} comparisons, binary {binary[0]:,}" f" (at most {bound} per query)")
if __name__ == "__main__": main()Sensor log report=================S1: 2016 readings, longest ok run 625 (2024-05-07T13:50 to 2024-05-11T21:50)S2: 2016 readings, longest ok run 307 (2024-05-07T16:50 to 2024-05-09T19:50)S3: 2016 readings, longest ok run 490 (2024-05-11T13:20 to 2024-05-14T22:50)S4: 2016 readings, longest ok run 199 (2024-05-08T02:20 to 2024-05-09T11:20)
Top 3 vibration readings of S4: 2024-05-12T06:40:00 18.98 mm/s fail 2024-05-13T01:30:00 18.57 mm/s fail 2024-05-04T10:30:00 17.73 mm/s fail
Rolling 1-hour max of S4 vibration: 2004 windows at fail level (>= 11.2 mm/s): 90 first one ends at 2024-05-01T08:00:00
S4 on 2024-05-13 00:00-06:00: 36 readings, mean vibration 6.47 mm/s
500 range queries: linear 1,008,000 comparisons, binary 10,978 (at most 22 per query)Run it from the project folder:
python sensor_queries.pyHow it works:
- Loading. One pass builds four lists in a
defaultdict(list). The sort per sensor costs only comparisons, because the file is already in time order (Timsort finds one run). It also protects the script from a file that is not sorted. - Range queries.
between()usesbisect_leftwithkey=lambda r: r[0], so it searches the readings by timestamp without building a separate list. The half-open rangestart <= t < endcomposes cleanly: 00:00–06:00 and 06:00–12:00 never count a reading twice. The night shift has 36 readings: 6 hours × 6 readings. - Streaks.
longest_run()keeps the start of the current run and resets it when the status changes: a variable-size window in one pass. S1 ran 625 readings, more than 4 days, without a warning; S4 only 199. - Top k.
heapq.nlargest(3, ...)keeps 3 candidates while it reads 2,016 readings. Two of the top 3 come from the wear period; the third is a spike on May 4. - Rolling maximum. The monotonic deque gives all 2,004 window maxima with at most two deque operations per reading. 90 windows contain a fail-level reading. The first ends at 08:00 on May 1: a single spike, long before the wear starts. A maintenance alarm should combine this signal with a rolling mean or median, as the lesson’s Example 8 showed.
- Proof of speed. The 500 queries cost 1,008,000 comparisons as scans (2,016 per query) and 10,978 with binary search: about 22 per query, the bound . The
assertinside the loop shows that both methods agree on every query.
Alternative: the range counts need only the timestamps, so a list times = [r[0] for r in s4] with plain bisect_left(times, start) works too, and is a little faster than key=. Keep the key= version when you need the readings themselves. With pandas (module 25), df.set_index("timestamp").loc[start:end] does the same binary search on a sorted index. Note that .loc label slicing includes end, unlike the half-open between().