第六章练习答案
iteration-protocol
python
class Range:
def __init__(self, start, end):
self.start = start
self.end = end
def __iter__(self):
return RangeIterator(self.start, self.end)
class RangeIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __next__(self):
if self.current < self.end:
value = self.current
self.current += 1
return value
raise StopIterationgenerators
python
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
list(fibonacci(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]