Iterators and Generators: Conceptual Solutions
What would python display?
>>> lstA = [7, 8, 3]
>>> lstB = [1, 2, 4, 6, 7, 8]
>>> iterA = iter(lstA)
>>> iterB = iter(lstB)
>>> next(lstA)
Error
>>> next(iterA)
7
>>> next(iterB)
1
>>> lstA = lstA + [1, 2, 5]
>>> list(iterA)
[8, 3]
>>> lstB.append(3)
>>>list(iterB)
[2, 4, 6, 7, 8, 3]
Code Writing
Fill in the even_iter class, which iterates through a list of numbers and gives only the even numbers.
class even_iter:
>> lst = [1, 3, 6, 7, 8, 4, 9]
>>> lit = even_iter(lst)
>>> next(lit)
6
>>> next(lit)
8
>>> next(lit)
4
def __init__(self, lst):
self.lst = lst
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.lst):
raise StopIteration Error
while self.lst[self.index] % 2 != 0:
self.index += 1
elem = self.lst[self.index]
self.index += 1
return elem
Write out a function that generates all factorials up to the nth.
def gen_factorial(n):
>> gen = gen_factorial(4)
>>> list(gen)
[1, 2, 6, 24]
count, fact = 1, 1
while count <= n:
fact = count * fact
yield fact
count += 1
Write out a function that generates the hailstone sequence.
(In case you don’t remember what that is: if n is even, divide n by 2, if n is odd, multiply by 3 and add 1 until n reaches 1)
def hailstone_gen(n):
>> gen = hailstone_gen(6)
>>> list(gen)
[6, 3, 10, 5, 16, 8, 4, 2, 1]
while n > 1:
yield n
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
yield n