Question about generators

Cameron Pulsford cameron.pulsford at gmail.com
Sun Jul 12 15:11:55 EDT 2009


Hey everyone, I have this small piece of code that simply finds the  
factors of a number.

import sys

def factor(n):
     primes = (6*i+j for i in xrange(1, n) for j in [1, 5] if (i+j)%5 ! 
= 0)

     factors = []

     for i in [2, 3, 5]:
         while n % i == 0:
             n /= i
             factors.append(i)
     for i in primes:
         while n % i == 0:
             n /= i
             factors.append(i)
     print factors

factor(int(sys.argv[1]))

My question is, is it possible to combine those two loops? The primes  
generator I wrote finds all primes up to n, except for 2, 3 and 5, so  
I must check those explicitly. Is there anyway to concatenate the hard  
coded list of [2,3,5] and the generator I wrote so that I don't need  
two for loops that do the same thing?

I tried writing a primes function using yield statements, but it  
didn't work like I thought it would.



More information about the Python-list mailing list