A dumb question about a class

Steven Bethard steven.bethard at gmail.com
Mon Aug 13 00:09:52 CEST 2007


Dick Moores wrote:
> I'm still trying to understand classes. I've made some progress, I 
> think, but I don't understand how to use this one. How do I call it, or 
> any of its functions? It's from the Cookbook, at 
> <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523048>.

The short answer is that use should look something like::

     >>> plist = PrimeList()
     >>> plist.contains(32)
     False
     >>> plist.contains(23)
     True

But this doesn't seem like a particularly good recipe. Seems like you 
would really rather be writing code like::

     >>> 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

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)


STeVe



More information about the Python-list mailing list