A dumb question about a class
Dick Moores
rdm at rcblue.com
Mon Aug 13 00:30:02 CEST 2007
At 03:09 PM 8/12/2007, Steven Bethard wrote:
>Here's how I'd write the recipe::
>
> import itertools
>
> def iter_primes():
> # an iterator of all numbers between 2 and +infinity
> numbers = itertools.count(2)
>
> # generate primes forever
> while True:
>
> # get the first number from the iterator (always a prime)
> prime = numbers.next()
> yield prime
>
> # remove all numbers from the (infinite) iterator that are
> # divisible by the prime we just generated
> numbers = itertools.ifilter(prime.__rmod__, numbers)
>
>
> class PrimeList(object):
> def __init__(self):
> # infinite iterator of primes
> self._prime_iter = iter_primes()
>
> # the last prime we've seen
> self._last_prime = None
>
> # all primes seen so far
> self._prime_set = set()
>
> # add the first prime (so that _last_prime is set)
> self._add_prime()
>
> def __contains__(self, n):
> # add primes to the list until we exceed n
> while n > self._last_prime:
> self._add_prime()
>
> # return True if n is one of our primes
> return n in self._prime_set
>
> def _add_prime(self):
> # take a prime off the iterator and update the prime set
> self._last_prime = self._prime_iter.next()
> self._prime_set.add(self._last_prime)
I'm afraid my next question is "How do I run this"?
Dick
More information about the Python-list
mailing list