Generating a list of EVEN numbers in Python

前端 未结 14 619
轻奢々
轻奢々 2021-01-17 15:48

Basically I need help in generating even numbers from a list that I have created in Python:

[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597         


        
14条回答
  •  执笔经年
    2021-01-17 16:30

    Instead of generating all Fibonacci numbers then filtering for evens, why not generate just the even values?

    def even_fibs():
        a,b = 1,2
        while True:
            yield b
            a,b = a+2*b, 2*a+3*b
    

    generates [2, 8, 34, 144, 610, 2584, 10946 ...]

    then your sum code becomes:

    total = 0
    for f in even_fibs():
        if f >= 4000000:
            break
        else:
            total += f
    

    or

    from itertools import takewhile
    total = sum(takewhile(lambda n: n<4000000, even_fibs()))
    

提交回复
热议问题