
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:
LapIteratoris a one-shot iterator. It remembers its position.Patrolis a reusable iterable. Eachiter()call gets a brand-newLapIterator.
p = Patrol(["dock", "mill"], laps=2)
print(list(p)) # ['dock', 'mill', 'dock', 'mill']
print(list(p)) # the same again!
Assignment
- In
LapIterator, make__iter__returnself. - Make
__next__hand out the stops in order, going roundlapstimes. Then raiseStopIteration(and keep raising it). - In
Patrol, make__iter__return a newLapIterator(self.stops, self.laps)every time. - Don't use
yieldhere: this checkpoint is about the protocol.
- In
LapIterator, make__iter__returnself. - Make
__next__hand out the stops in order, going roundlapstimes. Then raiseStopIteration(and keep raising it). - In
Patrol, make__iter__return a newLapIterator(self.stops, self.laps)every time. - Don't use
yieldhere: this checkpoint is about the protocol.
main.py Python sleeping
Press Run to try your code, then Check to test it.