A dumb question about a class
Steven Bethard
steven.bethard at gmail.com
Mon Aug 13 00:35:05 CEST 2007
Dick Moores wrote:
> 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"?
The same way I showed at the top (which you snipped in your reply)::
>>> plist = PrimeList()
>>> 1 in plist
False
>>> 2 in plist
True
>>> 22 in plist
False
>>> 23 in plist
True
>>> 782 in plist
False
>>> 787 in plist
True
The first line, ``plist = PrimeList()`` creates a PrimeList object and
names it ``plist``. You can then check whether a prime is in that
PrimeList object much like you might check a normal ``list`` or ``set``
object -- using the ``in`` operator as above.
Note that if you just want to iterate over all the primes, there's no
need for the class at all. Simply write::
for prime in iter_primes():
...
HTH,
STeVe
More information about the Python-list
mailing list