I am writing some code that is supposed to find the prime factorization of numbers. The main function increments through numbers; I'm doing that because I want to use the code to conduct timing experiments. I don't mind it not being super-efficient, part of the project for me will be making it more efficient myself. It is also not yet totally complete (for example, it doesn't simplify the prime factorization). I have tested all of the functions except the main function and they have worked, so there isn't a problem with those.
My code is
import math
import time
primfac=[]
def primes(n):
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
def factfind(lsp,n): #finds factors of n among primes
for i in lsp:
if n%i==0:
primfac.append(i)
else:
i+=1
def primfacfind(n1,n2):
while n1 < n2:
n = n1
time_start = time.clock()
factfind(primes(n),n)
print primfac
time_elapsed = time.clock() - time_start
print "time:", time_elapsed
primfac.clear()
n1+=1
print primfacfind(6,15)
And running it gives the output
[2, 3]
time: 7.5e-05
Traceback (most recent call last):
File "python", line 43, in <module>
File "python", line 39, in primfacfind
AttributeError: 'list' object has no attribute 'clear'
And I'm not really sure what is wrong. It is giving the right numbers for the prime factorization and it is printing the time, but it can't seem to clear the list. Commenting out the line primfac.clear()
has it working.
Any help would be appreciated. Thanks!
Python's list
does not have a clear
method until Python 3.x. Your code will not work in Python 2.x or earlier. You can either create a new list or delete all the contents of the old list.
#create a new list
primfac = []
#or delete all the contents of the old list
del primfac [:]
The list.clear()
method was added in Python 3.3. The equivalent can be achieved in earlier versions by del primfac[:]
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With