2015-04-05 105 views
0

該程序用於計算素數並將其保存到文件中。保存功能尚未正確編程,請忽略。該程序通過比較奇數與以前的素數進行工作。如果它不是這些數字的倍數,那麼它就是素數。從理論上講它應該然而,工作中當我嘗試通過從列表中返回的錯誤信息的質數來劃分數:錯誤消息:不支持的操作數類型___

Traceback (most recent call last): File "C:\Users\Archie\Desktop\maths python\prime\prime v1.3.py", line 51, in primeCheck(num) File "C:\Users\Archie\Desktop\maths python\prime\prime v1.3.py", line 8, in primeCheck check = int(num)/listImport TypeError: unsupported operand type(s) for /: 'int' and 'list'

能否請你無論是建議我該如何解決這個問題,或者提出一個不同的方法解決問題。

def primeCheck(num): 
    divider = 2 
    refresh = 0 
    firstPoint = 0 
    secondPoint = 1 
    while refresh == 0: 
     listImport = primeList[firstPoint:secondPoint] 
     check = int(num)/listImport 
     if (check.is_integer()): 
      refresh = 1 
     else: 
      firstPoint = firstPoint + 1 
      secondPoint = secondPoint + 1 
     if secondPoint > len(primeList): 
      file.write(str(num) + "\n") 
      print(str(num)) 
      global x 
      x = x + 1 
      refresh = 1 
      primeList.append 


\\  if (int(num)/divider).is_integer(): 
\\   if divider == num: 
\\    file.write(str(num) + "\n") 
\\    print(str(num)) 
\\    global x 
\\    x = x + 1 
\\    refresh = 1 
\\   else: 
\\    refresh = 1 
\\  else: 
\\   divider = divider + 1 

global file 
repeat = input("How many numbers do you want to add to the existing file?\n") 
file = open("Prime results v1.3.txt", "r") 
global x 
x = 1 
num = file.readline() 
file.close() 
global file 
file = open("Prime results v1.3.txt", "a") 
num = int(num) 

global primeList 
primeList = [2] 

while x <= int(repeat): 
    primeCheck(num) 
    num = num + 2 

file.close() 

該地區雙刀削減是我嘗試過,以前的方法工作,但這種方式更有效。

回答

0

有很多方法可以改善你的代碼。但是,錯誤的原因是,當你這樣做時,你會得到一個清單primeList[firstPoint:secondPoint]Explain Python's slice notation

當你想只索引列表中的一個項目,您可以通過使用my_list[idx]做到這一點:

更多有關此主題的SO問題是很好的解釋這裏(注:Python的索引從0開始),其返回列表my_list的位置idx的項目。

在我看來,firstPointsecondPoint之間的區別總是等於1(如果我理解你的代碼的話)。所以你根本不需要使用secondPoint。 只需編寫primeList[firstPoint]即可獲得與使用primeList[firstPoint:secondPoint]時相同的結果。

也有上線

primeList.append

這是一個功能,而不是函數調用中的錯誤。你可能想要做的:

primeList.append(num)

而另一個棘手的部分可能是,如果你使用Python2.x而不是Python 3中。兩個整數的0除法也是一個整數(例如4/3 = 0)。 所以我建議稍微修改:

check = float(num)/listImport 

4/3 = 1.3333333333333333而且is_integer()功能提出要求INT當錯誤(如果你使用Python 2.x的那麼int/int回報int並因此引發錯誤

。示例(Python 2.7):

>>> 1/4 
0 
>>> float(1)/4 
1.3333333333333333 
0

它看起來像你使用firstPointsecondPoint嘗試和索引primeList的特定元素。根據你當前的代碼,如果你使用的代碼是primeList = [2,3,5,7]firstPoint, secondPoint = 0, 1,那麼你有listImport = primeList[0:1] = [2] - 你最終得到一個包含你想要的元素的列表,這就是爲什麼它說你不能劃分一個int和一個列表。

相反,你會想索引到列表中。所以primeList[0]=2,primeList[1]=3等等。這樣你就可以結束實際的元素,而不是列表中的一部分,除此之外,你只需要跟蹤一個索引。

你可以閱讀更多關於Python列表操作here - 他們的文檔是全面和直觀的。

0

在第8行中,您嘗試通過列表劃分整數。這沒有定義。你想要的是用另一個整數來劃分整數。請注意,alist[i:i+1]仍然是一個列表。你想要alist[i],或者更好,用for item in list:迭代一個列表。

相關問題