Iterators and Generators: Conceptual
What would python display?
(Draw out environment diagram as well)
>>> lstA = [7, 8, 3]
>>> lstB = [1, 2, 4, 6, 7, 8]
>>> iterA = iter(lstA)
>>> iterB = iter(lstB)
>>> next(lstA)
______
>>> next(iterA)
______
>>> next(iterB)
______
>>> lstA = lstA + [1, 2, 5]
>>> list(iterA)
______
>>> lstB.append(3)
>>>list(iterB)
______
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 = ______
______
def __iter__(self):
return ______
def __next__(self):
if ______:
raise ______
while ______:
______ += 1
elem = ______
______ += 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 = ______
while ______:
fact = ______
yield ______
______
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, 4, 2, 1]
while ______:
yield ______
if ______:
______
else:
______
yield ______