我正在编写一个程序,其中包含一个函数,用于检查数字是否为素数 - 如果是,则将其添加到特定列表,然后使用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
文件显然在那里。
我该如何解决这个问题?提前感谢任何建议:)
答案 0 :(得分:2)
您已经发现了如何正确导入您的功能:
来自primenum import isPrime
或参考全名:
import primenum
primenum.isPrime(5)
您需要使用完整路径来存储您的pickle文件;否则python只在本地目录中查找它。也许将它存储在您的主目录中:
import os.path
HOME_DIR = os.path.expanduser('~')
然后用以下文件打开文件:
open(os.path.join(HOME_DIR, 'primes.pkl')