A Reusable Countdown
Write a class Countdown(n) such that looping over it gives n, n - 1, ..., 1.
- You must be able to loop over the same object more than once, and get the full sequence each time.
len(Countdown(5))must be5.Countdown(0)is empty.
Understand the problem
Separate the two roles.
What is the difference between an iterable and an iterator?
- There is none
- An iterable gives you a fresh iterator when you loop (it has
__iter__); an iterator produces the values and gets used up (it has__next__) - An iterator is always a list
A list is an iterable: each for loop calls iter(list) and gets a new iterator. The iterator keeps the position and is used up at the end. Because the iterable is not used up, you can loop over it many times.
A class defines __iter__ as return self and also __next__. Looping over one object twice does what?
- Gives the full sequence both times
- Gives the sequence the first time and nothing the second time
- Raises an error
The object is its own iterator, so it is used up after the first loop. This is the iterator pattern. For a reusable object, __iter__ must return a new iterator each time.
Write the solution
A class with __init__, __iter__ and __len__.
class Countdown:
# Write your code here.
pass
Hint 1: a question to ask yourself
What should __iter__ return, so that every loop starts afresh?
Hint 2: the shape of the answer
Store n in __init__. Make __iter__ return iter(range(n, 0, -1)), or make it a generator with yield. __len__ returns max(n, 0).
Reflect
Solution
class Countdown:
def __init__(self, n):
self.n = n
def __iter__(self):
return iter(range(self.n, 0, -1))
def __len__(self):
return max(self.n, 0)
Another way: iter as a generator
class Countdown:
def __init__(self, n):
self.n = n
def __iter__(self):
value = self.n
while value > 0:
yield value
value -= 1
def __len__(self):
return max(self.n, 0)
What this tests: the iteration protocol, the difference between an iterable and an iterator, __iter__, __len__, and generator methods.
The protocol: for x in obj calls iter(obj), which calls obj.__iter__(). That must return an iterator, which has __next__ and raises StopIteration at the end. A generator is an easy way to get one: writing yield inside __iter__ makes it return a new generator every time.
Iterable versus iterator: lists, tuples, dicts and your Countdown are iterables (reusable). Generators and file objects are iterators (single use).
len needs __len__: it is not available from __iter__. Providing it is polite, and list(Countdown(5)) uses it to pre-size the list.
What an interviewer might ask next: Write the one-shot iterator version (__iter__ returns self, plus __next__). When is it the better design? (When the data is a one-time stream, such as network input.)
VISIBLE = 3
CASES = [
('result = list(Countdown(3))', [3, 2, 1], 'a normal countdown'),
('c = Countdown(3)\nfirst = list(c)\nsecond = list(c)\nresult = (first, second)', ([3, 2, 1], [3, 2, 1]), 'the same object looped twice'),
('result = len(Countdown(5))', 5, 'a length'),
('result = list(Countdown(0))', [], 'an empty countdown'),
('result = sum(Countdown(4))', 10, 'it works with sum'),
('result = [x * 2 for x in Countdown(3)]', [6, 4, 2], 'it works in a comprehension'),
('result = len(Countdown(-3))', 0, 'a negative start is empty'),
('a = Countdown(2)\nb = iter(a)\nc = iter(a)\nresult = (next(b), next(c))', (2, 2), 'each loop has its own position'),
]