Steven Bethard <[EMAIL PROTECTED]> wrote in news:[EMAIL PROTECTED]:
> Steve Howell wrote: >> --- George Sakkis <[EMAIL PROTECTED]> wrote: >>> from itertools import count, ifilter >>> def sieve(): >>> seq = count(2) >>> while True: >>> p = seq.next() >>> seq = ifilter(p.__rmod__, seq) >>> yield p > [snip] >> Is there a way to broaden the problem somehow, so that >> it can be a longer solution and further down on the >> page, and so that I can continue to enforce my >> somewhat arbitrary rule of ordering examples by how >> long they are? > > How about we just comment it better? > > import itertools > > def iter_primes(): > # an iterator of all numbers between 2 and +infinity > numbers = itertools.count(2) > > # generate primes forever > while True > > # generate the first number from the iterator, > # which should always be a prime > prime = numbers.next() > yield prime > > # lazily remove all numbers from the iterator that > # are divisible by prime we just selected > numbers = itertools.ifilter(prime.__rmod__, numbers) > > I think that's 17-ish, though you could shrink it down by > removing some of the spaces. > > STeVe How about including a driver? Generators are frustrating for newbies (including oldies new to generators) because they don't actually do anything unless you know how to use them. Given the above, what's a newbie going to try first? Something like: >>> iter_primes() Hmmm. Doesn't do anything. How about >>> for ix in range(10): ... print iter_primes() Not what you might expect. Later: >>> for ix in range(10): ... print iter_primes().next() Hmmmmm.... ... and so on. In much of Python's documentation, and in this case, an occasional working example of use would go FAR in aiding understanding of the underlying concept. -- rzed -- http://mail.python.org/mailman/listinfo/python-list