ApathyBear
ApathyBear

Reputation: 9605

Python prime numbers generators in terminal

I have this code:

# Developing a program to generate all prime numbers

def gen_primes():
    n = 2
    primes = set()
    while True:
        for p in primes:
            if n%p == 0:
                break
        else:
            primes.add(n)
            yield n 
        n += 1

I may be way off but I assume the gen_primes().next () to begin with 2, then move on to the next prime number 3, and so on and so forth until the end of time. Yet when I access these values in terminal, they don't do that at all.

>>> for i in range(10):
...     gen_primes().next()
... 
2
2
2
2
2
2
2
2
2
2

and

>>> gen_primes().next()
2
>>> gen_primes().next()
2
>>> gen_primes().next()
2
>>> gen_primes().next()
2

What is going on here that I am unaware of? As a side note I am importing the script (as a module) if it matters at all.

Upvotes: 2

Views: 143

Answers (1)

thefourtheye
thefourtheye

Reputation: 239553

gen_primes() creates a new generator object every time. Instead, store it in a variable and use next, like this

>>> primes = gen_primes() 
>>> for _ in range(10):
...     next(primes)
...     
... 
2
3
5
7
11
13
17
19
23
29

Instead of you iterating the iterable, leave that to the built-in itertools.islice module, like this

>>> from itertools import islice
>>> for prime in islice(gen_primes(), 10):
...     print(prime)
...     
... 
2
3
5
7
11
13
17
19
23
29

Upvotes: 4

Related Questions