Generators/iterators, Pythonicity, and primes
Mark Tolonen
metolone+gmane at gmail.com
Sat Apr 4 21:06:57 CEST 2009
"John Posner" <jjposner at snet.net> wrote in message
news:AF9FBCC3A7624599A6F51BAD2397EA46 at AMDUP...
> Inspired by recent threads (and recalling my first message to Python
> edu-sig), I did some Internet searching on producing prime numbers using
> Python generators. Most algorithms I found don't go for the infinite,
> contenting themselves with "list all the primes below a given number".
>
> Here's a very Pythonic (IMHO) implementation that keeps going and going
> and
> going ...:
>
> from itertools import count
> from math import sqrt
>
> def prime_gen():
> """
> Generate all prime numbers
> """
> primes = []
> for n in count(2):
> if all(n%p for p in primes if p < sqrt(n)):
> primes.append(n)
> yield n
p <= sqrt(n) works a little better :^)
-Mark
More information about the Python-list
mailing list