Python 脚本挂起,可能是无限循环?
再次参与欧拉计划,这次我的脚本只是挂在那里。我很确定我让它运行了足够长的时间,而且我的手迹(正如我父亲所说的那样)不会产生任何问题。我哪里出错了?
我只包含代码的相关部分一次。
def main():
f, n = 0, 20
while f != 20:
f = 0
for x in range(1,21):
if n % x != 0: break
else: ++f
if f == 20: print n
n += 20
提前致谢!
Once again working on Project Euler, this time my script just hangs there. I'm pretty sure I'm letting it run for long enough, and my hand-trace (as my father calls it) yields no issues. Where am I going wrong?
I'm only including the relevant portion of the code, for once.
def main():
f, n = 0, 20
while f != 20:
f = 0
for x in range(1,21):
if n % x != 0: break
else: ++f
if f == 20: print n
n += 20
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python 没有增量 (
++
)。它被解释为+(+(a))
。 + 是一元加运算符,它基本上不执行任何操作。使用+= 1
Python doesn't have increment (
++
). It's interpreted as+(+(a))
. + is the unary plus operator, which basically does nothing. Use+= 1
在你的情况下,“f”值永远不会达到 20,因此永远不会退出
1) 在第一次中断时(当 n=20 且 x =3 时),它再次设置 f=0。
类似地,对于下一个循环,n 也会增加 20,但是当 'x' 再次为 3 时,相同的 f=0
所以这将进入无限循环......
Here in your case 'f' value can never reach 20 and hence never exit
1) At 1st break (when n=20 and x =3) it again set f=0.
Similarly for next loop also n get increased 20 but when 'x' is 3 again same f=0
So this will go in infinite loop....