python练习题第一题:

2017-08-31  本文已影响21人  elaine0622

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.

代码如下:

sequence = []
sequence.append(1)
sequence.append(2)
while sequence[-1] < 4e6:
    end = sequence[-2] + sequence[-1]
    sequence.append(end)
if sequence[-1] > 4e6:
    sequence.pop()

total = 0
for i in range(1, len(sequence) + 1):
    if (i - 1) % 2 == 0:
        total = total + sequence[(i - 1)]
print total
上一篇下一篇

猜你喜欢

热点阅读