Checkpoint

Checkpoint: The Night Patrol

The Lantern Guild sends a night patrol around the harbor. The patrol walks the same stops several times (each full round is a lap). Captains loop over the patrol plan many times, even in nested loops, so it must never "run dry".

This checkpoint uses both roles from this chapter:

  • LapIterator is a one-shot iterator. It remembers its position.
  • Patrol is a reusable iterable. Each iter() call gets a brand-new LapIterator.
p = Patrol(["dock", "mill"], laps=2)
print(list(p))  # ['dock', 'mill', 'dock', 'mill']
print(list(p))  # the same again!

Assignment

  1. In LapIterator, make __iter__ return self.
  2. Make __next__ hand out the stops in order, going round laps times. Then raise StopIteration (and keep raising it).
  3. In Patrol, make __iter__ return a new LapIterator(self.stops, self.laps) every time.
  4. Don't use yield here: this checkpoint is about the protocol.