美文网首页
python练习题第一题:

python练习题第一题:

作者: elaine0622 | 来源:发表于2017-08-31 11:03 被阅读21次

    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
    

    相关文章

      网友评论

          本文标题:python练习题第一题:

          本文链接:https://www.haomeiwen.com/subject/fuxqjxtx.html