1
# 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 万个循环,虽然它不影响整体答案,但我对它的存在方式感到困惑。

先谢谢了

4

1 回答 1

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)
于 2013-05-25T10:45:10.717 回答