Reputation: 1
The result of below program is
2 step 3 step 5 step 7 step
How does yield run? What does yield return, by n
or it's generator
?
Why isn't number 9's answer the result (2 step 3 step 5 step 7 step step
)?
Can you explain how the program is run?
def _odd_iter():
n = 1
while True:
n = n+2
yield n
def _not_divisible(n):
return lambda x:x%n >0
def primes():
yield 2
it = _odd_iter()
while True:
print('step')
n = next(it)
yield n
it = filter(_not_divisible(n),it)
c = primes()
for i in c:
if i<10:
print(i)
else:
break
Upvotes: 0
Views: 72
Reputation: 657
What the program is doing is determined by the for
-loop in the last five lines. The loop is consuming primes (2, 3, 5, 7, 11, 13, ...) produced by the generator c
.
c
does not produce 9 because 9 is not a prime (it is divisible by 3).
And the program is not printing 11, 13, ... because the for
-loop is exited when i
becomes 11 (11 is not less than 10).
Upvotes: 1