# 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[]
结果如下:
^{pr2}$我在ProjectEuler上检查了答案,结果是正确的,这很好:D但是有一件事我不确定,当它按顺序打印出数字列表时,它的末尾有一个数字:5702887。这已经超过了400万个循环,虽然它不影响整个答案,但我很困惑它是如何存在的。在
提前感谢:D
考虑一下这段代码
现在考虑一下
fibon[-1]
包含3524578的情况。由于条件是true
,循环将运行,并在序列中添加和追加下一个数字,即5702887。在现在条件变成
false
,循环结束。在编辑:为了避免它,您可以这样做。在
^{pr2}$相关问题 更多 >
编程相关推荐