[Edu-sig] Scratch pad nuttiness... (re generators)

kirby urner kirby.urner at gmail.com
Tue Mar 17 02:22:18 CET 2009


Writing for the Linux Gazette, Pramode C.E. shows us a nifty set of
generators for sieving out composites, adapted for Python 3 in the
source code below.  Is this really a sieve or trial-by-division?

http://linuxgazette.net/100/pramode.html

def firstn(g, n):
	for i in range(n):
		yield next(g)

def intsfrom(i):
	while True:
		yield i
		i = i + 1

def exclude_multiples(n, ints):
	for i in ints:
		if (i % n): yield i

def sieve(ints):
	while True:
		prime = next(ints)
		yield prime
		ints = exclude_multiples(prime, ints)
	
if __name__ == '__main__':
	for i in firstn(sieve(intsfrom(2)), 400):
		print(i)


More information about the Edu-sig mailing list