我正在寫一個程序,它包含一個函數,用於檢查數字是否爲素數 - 如果是,則將其添加到特定列表中,然後使用pickle
模塊將其另存爲文件。當功能再次被調用時,它會打開列表(使用pickle
),然後檢查數字是否在列表中。如果是這樣,它是一個主要的,如果不是,它會使用一個非常基本的技術來檢查它是否是一個素數。Python命令處理器 - 在我的代碼問題?
這裏是我的代碼:
'''
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外殼。
發生的錯誤是如果函數實際調用。我通過做from primenum import isPrime
來完成這個任務。但是,那麼它會得到一個錯誤與I/O(與pickle
)......這裏有一個畫面:
正如你所看到的,primes.pkl
文件是明顯存在的。
我該如何解決這個問題?在此先感謝您已經發現瞭如何正確導入您的功能有任何建議:)
所以,你*是*可以通過根據道路Python導入實際導入的方式運行的功能,工作。那麼你在第一部分究竟究竟在問什麼? –
您可以複製終端中的文本並將其粘貼到SO上的編輯器中。使用編輯器工具欄上的「{}」按鈕(選擇您的代碼)對其進行正確格式化。不需要在這裏使用這麼多的截圖,這全是文字。 –
另外,我們通常談論Python交互式shell而不是Python命令處理器。 –