我正在编写一个程序,其中包含一个检查数字是否为素数的函数---如果是,它将其添加到特定列表中,然后使用pickle
模块将其保存为文件。当再次调用该函数时,它会打开列表(使用pickle
),然后检查该号码是否在列表中。如果是,它是一个素数,如果不是,它使用一种非常基本的技术检查它是否是一个素数。
这是我的代码:
'''
List of functions:
_isPrime(n)_ : checks if n is a prime number
_remove(n)_ : removes n from the running list of primes and updates the pkl file
_prevPrimes(n)_ : generates a list of primes up to n
_view()_ : imports and prints pList
_delete()_ : deletes all of pList
'''
def isPrime(n):
import pickle
from math import sqrt
pList = pickle.load(open('primes.pkl', 'rb'))
x=2
if (type(n) != int) and (type(n) != long):
print "N is not an integer."
return False
if n in pList:
print "%d is a prime number." % (n)
return True
else:
while (sqrt(n) >= x):
if ((n%x) != 0):
x = x + 1
if (sqrt(n) < x):
pList.append(n)
pList = sorted(pList)
pickle.dump(pList, open('primes.pkl', 'wb'))
print "%d is a prime number." % (n)
return True
if ((n%x)==0):
print "%d is not a prime number." % (n)
return False
pList = sorted(pList)
pickle.dump(pList, open('primes.pkl', 'wb'))
# NEW FUNCTION
def prevPrimes(n):
from time import clock
startTime= clock()
import pickle
from math import sqrt
pList = pickle.load(open('primes.pkl', 'rb'))
z = abs((max(pList)) - n)
y= max(pList)
if (z==0):
print "Done"
while (y <= n):
pList = pickle.load(open('primes.pkl', 'rb'))
if isPrime(y):
if y not in pList:
pList.append(y)
y= y + 1
pList = sorted(pList)
pickle.dump(pList, open('primes.pkl', 'wb'))
print startTime
# NEW FUNCTION
def remove(n):
import pickle
pList = pickle.load(open('primes.pkl', 'rb'))
view()
pList.remove(n)
pickle.dump(pList, open('primes.pkl', 'wb'))
view()
# NEW FUNCTION
def view():
import pickle
pList = pickle.load(open('primes.pkl', 'rb'))
print pList
# NEW FUNCTION
def delete():
import pickle
pList = [2, 3, 5]
pickle.dump(pList, open('primes.pkl', 'wb'))
view()
它在 Python shell 中运行良好。
发生的错误是函数是否实际调用。我通过这样做完成了这一点from primenum import isPrime
。但是,它会在 I/O(带有pickle
)时出现错误......这是一张图片:
如您所见,primes.pkl
文件显然在那里。
我该如何解决?在此先感谢您的任何建议 :)