Code

Endless Streams with itertools

The itertools module is a toolbox of lazy iterators:

Tool What it does
count(start) start, start+1, ... forever
cycle(items) repeats items forever
islice(it, n) takes the first n items (lazily)
chain(a, b) a then b, like yield from
groupby(it) groups consecutive equal items
from itertools import count, cycle, islice, groupby

colors = cycle(["red", "gold"])
print(list(islice(colors, 3)))  # ['red', 'gold', 'red']

for key, group in groupby("aaabcc"):
    print(key, len(list(group)))  # a 3 / b 1 / c 2

Endless streams are safe as long as something (islice, zip, next, break) decides when to stop.

Careful: groupby only groups items that sit next to each other. groupby("abab") gives four groups. Sort first if you want one group per key.

Assignment

  1. lantern_ids(prefix): an endless generator yielding "L-1", "L-2", ... for prefix "L" (use count).
  2. watch_rota(guards, shifts): return a list of (shift_number, guard) tuples for the first shifts shifts. Shifts are numbered from 1 and guards take turns in order, repeating forever.
  3. compress_runs(text): return a list of (char, run_length) tuples using groupby. compress_runs("aaabcc") is [("a", 3), ("b", 1), ("c", 2)].