progress

~/problems / Iterators & parsers / Iterators and generators

Collapse repeated sensor readings

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 humidity sensor reports every second, and the value rarely changes. Before sending the stream over a slow radio link, collapse each run of equal consecutive readings into one (value, count) pair, lazily: the stream never ends.

Implement class Runs:

  • Runs(iterable) wraps any iterable, including infinite ones, and yields (value, count) for each maximal run of consecutive equal items (==). Equal values that aren't adjacent form separate runs.
  • iter(runs) returns itself; once exhausted, next() keeps raising StopIteration.
  • To end a run you must read one item past it. Keep that item for the next run, and never read further ahead.
list(Runs([55, 55, 55, 56, 55, 55]))   # [(55, 3), (56, 1), (55, 2)]
list(Runs("aab"))                       # [("a", 2), ("b", 1)]
list(Runs([]))                          # []

import itertools
r = Runs(itertools.cycle([1, 1, 2]))    # 1 1 2 1 1 2 ...
next(r)   # (1, 2)
next(r)   # (2, 1)
next(r)   # (1, 2)

Use a class with __iter__ and __next__ (no generator function, no itertools.groupby).

Show hint

store iter(iterable) and a "pending" item, with a sentinel _EMPTY = object() for "nothing held". Take the pending item (or pull one), then pull while items equal it; the first different one becomes pending.

Topic: Iterators and generators. Resumable/serializable iterators, merging streams, lazy pipelines.

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