progress

~/problems / Pools & pipelines / Ring buffers and producer/consumer pipelines

Greenhouse thermometer log

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

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 length capacity made once in __init__; track the oldest position and the count yourself, wrapping with % capacity (no deque, pop(0), slicing off the front or growing).
  • record(x): store integer x, dropping the oldest if full.
  • __len__(): readings stored.
  • recent(k) -> list[int]: the last min(k, len) readings, oldest first.
  • mean() -> float | None: the average, or None if 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].

Topic: Ring buffers and producer/consumer pipelines. Fixed-size circular buffers, head/tail indexes, back-pressure.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc