A greenhouse controller keeps only the last capacity temperature readings: when full, a new reading overwrites the oldest. It asks for the average all the time.
Implement ReadingLog(capacity) (single-threaded):
- Keep readings in
self.buf, a list of lengthcapacitymade once in__init__; track the oldest position and the count yourself, wrapping with% capacity(nodeque,pop(0), slicing off the front or growing). record(x): store integerx, dropping the oldest if full.__len__(): readings stored.recent(k) -> list[int]: the lastmin(k, len)readings, oldest first.mean() -> float | None: the average, orNoneif empty.
log = ReadingLog(3)
log.mean() # None
log.record(20); log.record(22); log.record(27)
log.mean() # 23.0
log.record(19) # full: overwrites 20
log.recent(5) # [22, 27, 19]
log.recent(2) # [27, 19]
log.mean() # 22.666... (68 / 3)
len(log) # 3
⭐ Bonus: summing the buffer in mean() still passes; a speed test calling mean() after each of 200,000 readings earns a star if mean() is O(1) (keep a running total).
Show hint
when full, write over buf[head] (subtracting it from the total) and advance head; otherwise write at buf[(head + size) % capacity]. The i-th oldest is buf[(head + i) % capacity].