项目Euler 2:正确的答案,但在代码中困扰我的事情

时间:2013-05-25 10:38:20

标签: python loops

# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

fibon = [1, 2] # The first 2 numbers in the sequence
addtoend = 0 # The number that will be added to the end of the sequence
evens = [] # Will hold the even numbers in the sequence

while fibon[-1] <= 4000000: # Starts the While loop
    addtoend = fibon[-1] + fibon[-2] # Sets addtoend equal to the last two items in fibon[]
    fibon.append(addtoend) # Appends addtoend onto the end of fibon[]

print fibon # Print out fibon[]

for i in fibon: # Starts the for loop
    if i % 2 == 0: # If the remainder of the current item in the list when divided by 2 is 0...
        evens.append(i) # Then add it to the evens[] list
    else: # Otherwise...
        pass # Just skip it

print evens # Print the evens array, with all the even numbers from fibon[] inside it.
print sum(evens) # Print the sum of all the even numbers from evens[]

这给出了结果:

[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887]
[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
4613732

我检查了Euler项目的答案,这是正确的,这很好:D但是我不确定的一件事是,当它打印出序列中的数字列表时,它有数字: 5702887 到底。这超过了400万的循环,虽然它不影响整体答案,但我对它是如何存在感到困惑。

提前致谢:D

1 个答案:

答案 0 :(得分:3)

考虑这段代码

while fibon[-1] <= 4000000:
    addtoend = fibon[-1] + fibon[-2] 
    fibon.append(addtoend)

现在考虑fibon[-1]包含3524578的情况。由于条件为true,循环将运行,并添加并附加序列中的下一个数字,即5702887。

现在条件变为false并且循环结束。

编辑:为了避免这种情况,您可以执行以下操作。

while True:
    addtoend = fibon[-1] + fibon[-2]
    if addtoend > 4000000: break
    fibon.append(addtoend)