Sent today to python-list ... 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 The use of all() is particularly nifty (see http://code.activestate.com/recipes/576640/). And so is the way in which the list comprehension easily incorporates the sqrt(n) optimization. Question: Is there a way to implement this algorithm using generator expressions only -- no "yield" statements allowed? E-mail message checked by Spyware Doctor (6.0.0.386) Database version: 5.12110 http://www.pctools.com/en/spyware-doctor-antivirus/ _______________________________________________ Edu-sig mailing list Edu-sig@python.org http://mail.python.org/mailman/listinfo/edu-sig