Python generators two clearly identical programs work differently

The program below [Python 3.4] is a simple Eratoshenes sieve:

from itertools import * def excl(ns,pr): return (i for i in ns if i%pr) def sieve(ns): while True: pr=next(ns) yield pr ns=excl(ns,pr) # ns=(i for i in ns if i%pr) r=list(islice(sieve(count(2)),10)) 

which produces [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]. OK. Uncommenting the line in which inline excl (), and commenting out the call, gives [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]. Why?

Is this related to the problems that arise when modifying a sequence within a loop that iterates over it?

Thanks for any hint.

+6
source share
1 answer

Your problem is that the pr referenced by the generator expression is the same pr that you change in the next iteration of the while loop, so every number that is not divisible by the previous β€œprime” number is treated as β€œprime”. Which itself changes pr , etc. In the excl function that you call pr is one that is passed as an argument that never changes.

+2
source

All Articles