新手 pythoer 求大家看一个小程序

2015-10-10 15:24:21 +08:00
 theohateonion
def is_prime(x):
if x <= 1:
        return False
    if x == 2:
        return True
    for i in range(2,x):
        if x % i == 0:
            return False            
        else:
            return True

自己写的一个判断素数的小程序,但是不知道为什么会把 9 , 15 等这些数判为素数。。

2791 次点击
所在节点    Python
15 条回复
zzy8200
2015-10-10 15:28:53 +08:00
去掉 else
saber000
2015-10-10 15:32:47 +08:00
姑且认为第一行的缩进被吞了,else 和下面的代码往左一个缩进
BraveRBT
2015-10-10 15:34:33 +08:00
注意缩进对其
另外应该是 Pythoner~?
zzy8200
2015-10-10 15:38:24 +08:00
去掉 else:后把 return True 拿到最外面,你这个只会判断是否是偶数
BraveRBT
2015-10-10 16:34:48 +08:00
直接给楼主附上修改后的代码咯 :)
def is_prime(x):

if x <= 1:
return False
if x == 2:
return True
for i in range(2,x):
if x % i == 0:
return False
return True
BraveRBT
2015-10-10 16:35:55 +08:00
不好意思
<pre>
def test_prime(x):
if x <= 1:
return False
if x == 2:
return True
for i in range(2,x):
if x % i == 0:
return False
return True
</pre>
BraveRBT
2015-10-10 16:37:49 +08:00
没搞懂 V2EX 的回复格式,哪位指导一下
Thanks
imlonghao
2015-10-10 16:48:51 +08:00
@BraveRBT 回帖不支持 Markdown ,使用 gist 可破
twor2
2015-10-10 16:49:36 +08:00


PS: @BraveRBT 回复不支持 md ,只有发帖支持
twor2
2015-10-10 16:50:50 +08:00
billgreen1
2015-10-10 16:59:37 +08:00
看看各种筛法吧
Arnie97
2015-10-10 17:09:09 +08:00
新手大概不知道 list comprehension ?

(x > 1) and all(x % i for i in range(2, x))
twor2
2015-10-10 17:21:01 +08:00
@Arnie97 新手,知道,但用得少,没意识,没有形成条件反射
BraveRBT
2015-10-11 21:21:52 +08:00
@imlonghao
@twor2
了解了 Thanks~!
theohateonion
2015-10-12 07:38:34 +08:00
谢谢各位啦。我找到问题了~

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/226928

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX