Question about generators
Mensanator
mensanator at aol.com
Sun Jul 12 15:47:46 EDT 2009
On Jul 12, 2:11 pm, Cameron Pulsford <cameron.pulsf... at gmail.com>
wrote:
> 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?
Yeah, get rid of the first loop.
> 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?
primes.extend([2,3,5])
>
> 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