【发布时间】:2014-01-10 18:30:05
【问题描述】:
这是来自我正在学习 Python 的 codeacademy.com 的一个问题。 所以我想要的是定义一个检查数字是否为素数的函数。 如果是,则返回 True。 如果不是,则返回 False。
这是我的代码:
def is_prime(x):
lst = [] # empty list to put strings 'False' and 'True'
for i in range(2,x): # starting at 2 and not including x (number 1 is a divisor of all numbers
if x <= 2: # [1] see bellow the explanation
lst.append('False')
break
elif x % i == 0: # if x is divisible by i(number between 2 and not including x)
lst.append('False')
break # break, because we already know x is not prime
elif x % i > 0:
lst.append('True') # x is not divisible by i
if 'False' in lst:
return False # x is not prime - return False
else:
return True # 'True' is in lst, so x is prime - return True
print is_prime(-2) # [2] I get an error here. See below
[1] - 我提出这个条件是因为在 codeacademy 中它说: “暗示 记住:所有小于 2 的数都不是素数!”
[2] - 例如,当我运行 'print is_prime(11)' 或 'is_prime(6)' 时,它工作正常。所以我提交了答案,但 codeacademy 不接受它。它说: “你的函数在 is_prime(-2) 上失败。它应该返回 False 时返回 True。”
【问题讨论】:
-
您好,欢迎来到 StackOverflow。实际上,这是一个非常好的问题,并且您已经提供了重现问题所需的所有信息 - 这对于 StackOverflow 的第一张海报来说是非常罕见的。恭喜你(以及你的英语)。很高兴有你在这里!
-
我强烈推荐 pythontutor.com 用于可视化执行:如果你去那里,并将代码粘贴到执行窗口中,你会明白为什么你会得到
Trueforis_prime(-2)。 -
除此之外,如果你想找到素数,你不需要检查
2和x之间的所有数字——int(math.sqrt(x))是一个足够高的上限。 -
就和@TimPietzcker 所说的一样,只需 +1 问题...如果 SO 上的每个人都可以这样,在你这个年纪... :)
-
谢谢大家!你真的激励我继续这个很棒的编程世界......
标签: python math numbers primes