简体   繁体   English

为什么我的Python脚本会永远运行?

[英]Why does my Python script run forever?

Here is the code: 这是代码:

numbers = [1, 2]
while new < 1000:
    new = 0
    x = int(len(numbers) - 1)
    new = numbers[x] + numbers[x-1]
    if new % 2 == 0:
        numbers.append(new)
    new += 1
print sum(numbers)

What did I do wrong? 我做错了什么? Criticism is welcome. 欢迎批评。 Thanks for your time. 谢谢你的时间。

This is basically because of the following condition - 这基本上是由于以下情况-

if new % 2 == 0:

coupled with the line - new=number[x] + number[x-1] at the start of the loop. 在循环开始时与行new=number[x] + number[x-1]耦合。

The first fibonacci number you calculate is 3 , because of the above condition , it is never actually added to number , and hence in every loop you are again calculating the same 1+2 , since number is never actually changed. 由于上述条件,您计算出的第一个斐波那契数是3 ,因此它实际上并不会加到number ,因此,在每个循环中,您都将再次计算相同的1+2 ,因为number实际上并没有改变。

The issue is not because of the line - new=0 at the start of the loop like other answer are explaining (that line has no effect at all , you can remove it and see same results). 问题不是因为该行-循环开始时new=0就像其他答案所解释的那样(该行完全无效,您可以将其删除并看到相同的结果)。

If your aim is to get the list of all even fibonacci numbers, then you can do - 如果您的目标是获取所有偶数斐波那契数字的列表,那么您可以-

numbers = [2]
a, b = 1, 2
while b < 1000:
    x = int(len(numbers) - 1)
    a, b = b, a+b
    if b % 2 == 0:
        numbers.append(b)
print sum(numbers)

Demo - 演示-

>>> numbers = [2]
>>> a, b = 1, 2
>>> while b < 1000:
...     x = int(len(numbers) - 1)
...     a, b = b, a+b
...     if b % 2 == 0:
...         numbers.append(b)
...
>>> print(sum(numbers))
798

The problem is that nothing really gets updated. 问题是什么都没有真正更新。

numbers = [1, 2]
while new < 1000:
    new = 0  #you're resetting new here
    x = int(len(numbers) - 1)
    new = numbers[x] + numbers[x-1] # first iteration, gives 3
    if new % 2 == 0:  # 3 % 2 != 0, so it doesn't get run
        numbers.append(new)
    new += 1 # great, new is now 1.
print sum(numbers)

Every iteration of the loop runs like this because nothing ever changes. 循环的每次迭代都是这样运行的,因为没有任何变化。 If you wanted to do fibonacci, you would do something like this 如果你想做斐波那契,你会做这样的事情

numbers = [1, 2]
for _ in range(1000)
    n = numbers[-1] + numbers[-2] # use negative indices to count from the end.
    numbers.append(n)
print sum(numbers) # sum of fibonacci I guess

Every time you add one to the variable new in your loop, you set it back to 0 when you reiterate the loop! 每次在循环中向new变量添加一个时,您在重复循环时都将其设置回0 This means that new will never reach 1000--it will continue forever in the loop. 这意味着new永远不会达到1000,它将永远循环下去。

To fix this, move the initialization of new outside of the loop. 要解决此问题,请将new的初始化移到循环外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM