A dumb question about a class

Dick Moores rdm at rcblue.com
Sun Aug 12 20:01:19 EDT 2007


At 03:35 PM 8/12/2007, Steven Bethard wrote:
>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():

Even if I want to test only 1 integer, or want the list of primes in 
a certain interval, I don't need the class at all:

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

def listPrimes(n,m):
     """
     Returns the list of primes in closed interval [n,m]
     """
     primes = []
     for prime in iter_primes():
         if prime > m:
             return primes
         if n <= prime <= m:
             primes.append(prime)
============================================

Thanks for your help. I didn't learn much about classes, but 
appreciated your iter_primes() a lot!

Dick Moores 




More information about the Python-list mailing list