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.


In [1]:
def gen_fibonacci():
    a, b = 0, 1
    while True:
        a, b = b, a + b 
        yield b

In [2]:
def gen_even(gen):
    for i in gen:
        if i%2 == 0:
            yield i

In [3]:
def gen_lte(gen, n): 
    for i in gen:
        if i > n:
            break
        yield i

In [4]:
n = 4000000
%timeit sum(gen_lte(gen_even(gen_fibonacci()), n))
sum(gen_lte(gen_even(gen_fibonacci()), n))


100000 loops, best of 3: 17 us per loop
Out[4]:
4613732