>>>>> Cameron Pulsford <[email protected]> (CP) wrote:
>CP> Hey everyone, I have this small piece of code that simply finds the
>CP> factors of a number.
Others have already given you advice to add the [2, 3, 5] to the
iterator (of which the primes.extend([2,3,5]) will not work). Please
allow me to make some other remarks.
>CP> import sys
>CP> def factor(n):
>CP> primes = (6*i+j for i in xrange(1, n) for j in [1, 5] if (i+j)%5 ! = 0)
It is a bit misleading to call this `primes' as it will also contain
non-primes. Of course they don't harm as they will never be considered a
factor because all their prime factors will have been successfully
removed before this non prime will be considered.
>CP> factors = []
>CP> for i in [2, 3, 5]:
>CP> while n % i == 0:
>CP> n /= i
>CP> factors.append(i)
>CP> for i in primes:
>CP> while n % i == 0:
>CP> n /= i
>CP> factors.append(i)
You can stop the loop when n == 1. Like:
if n == 1: break
>CP> print factors
>CP> factor(int(sys.argv[1]))
>CP> My question is, is it possible to combine those two loops? The primes
>CP> generator I wrote finds all primes up to n, except for 2, 3 and 5, so I
>CP> must check those explicitly. Is there anyway to concatenate the hard coded
>CP> list of [2,3,5] and the generator I wrote so that I don't need two for
>CP> loops that do the same thing?
>CP> I tried writing a primes function using yield statements, but it didn't
>CP> work like I thought it would.
See the recent thread `Why is my code faster with append() in a loop than with
a large list?'
http://mail.python.org/pipermail/python-list/2009-July/718931.html
--
Piet van Oostrum <[email protected]>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
--
http://mail.python.org/mailman/listinfo/python-list