~/cs2613/labs/L18
Consider the countdown
generator from Section 6.2
def countdown(n):
print('Counting down from', n)
while n > 0:
yield n
n -= 1
Referring to Section
6.1
an equivalent iterator class. Here we will implement the entire protocol with one class, but multiple classes like we did for JavaScript is also reasonable.
Modify only the __next__
method of the following skeleton class so that given
tests pass.
def countdown(n):
yield 'starting'
while n > 0:
yield n
n -= 1
def test_generator():
counter = countdown(3)
assert [ t for t in counter ] == \
['starting', 3, 2, 1]
class Counter:
"Iterator class simulating countdown"
def __init__(self,n):
self.n = n
self.first = True
def __iter__(self):
return self
def __next__(self):
# insert code here
self.n -= 1
return self.n+1
def test_class():
counter = Counter(3)
assert [ t for t in counter ] == \
['starting', 3, 2, 1]
__iter__
for?Update the __iter__
method of your previous solution so that the following additional test passes
def test_twice():
counter = Counter(3)
assert [ t for t in counter ] == \
['starting', 3, 2, 1]
assert [ t for t in counter ] == \
['starting', 3, 2, 1]
Note that 6.5 just asks you to run some code, but you do have to be in the correct directory when running it.
For 6.6, you essentially need to split the given code so that the
first part is the new generator follow
.
Start with the following stock related classes:
Complete Exercise
6.7. I
suggest you make a new file follow2.py
so that you preserve
solutions for 6.6 and 6.7.