我正在写一些代码,用来寻找数的素因子分解。主函数通过数字递增;我这样做是因为我想使用代码进行计时实验。我不介意它不是超级高效,对我来说,项目的一部分将是让它更高效自己。它还没有完全完成。你知道吗
import math
import time
primfac=[]
def primcheck(n):
for x in xrange(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
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 simplify(lsp, n):
x = 1
for i in lsp:
x=i*x
if x != n:
print "needs exponent, computing"
for i in lsp:
y=n/i
if primcheck(y) == True:
lsp.append(y)
else:
lsp.append(factfind(primes,y))
def primfacfind(n1,n2):
while n1 <= n2:
time_start = time.clock()
if primcheck(n1) == True:
print "prime"
time_elapsed = time.clock() - time_start
print "time:", time_elapsed
n1+=1
else:
n = n1
print "starting #", n
factfind(primes(n),n)
print primfac
del primfac
primfac[:] = []
simplify(primfac, n)
time_elapsed = time.clock() - time_start
print "time:", time_elapsed
n1+=1
primfacfind(6,15)
当我运行代码时,它会给出以下错误消息:
Traceback (most recent call last):
File "python", line 65, in <module>
File "python", line 54, in primfacfind
UnboundLocalError: local variable 'primfac' referenced before assignment
我不明白,因为我已经测试了除了simplify
函数之外的所有函数,即使这样,唯一的新部分还是print
之后的行。你知道吗
python中的函数只能以只读方式访问在函数范围之外声明的变量,而不使用global关键字。你知道吗
相关问题 更多 >
编程相关推荐