2015-04-05 88 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:迭代一个列表。

相关问题