0

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
Davy M
  • 1,697
  • 4
  • 20
  • 27
ivanrres
  • 1
  • 1
  • 4
    Possible duplicate of [What does the "yield" keyword do?](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do) – Davy M Aug 09 '17 at 15:39
  • If you want 9 to appear, get rid of the line `it = filter(_not_divisible(n),it)`. Of course, then you're no longer emitting primes... – Scott Mermelstein Aug 09 '17 at 17:45
  • @ivanrres Did my post answer your question? If not, what is still unclear? – yogabonito Aug 13 '17 at 16:06

1 Answers1

1

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).

yogabonito
  • 657
  • 5
  • 14