Project Euler: Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 0 and 1, the first 12 terms will be:

0, 1, 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 [19]:
def fibonacci():
        x,y = 0,1
        while True:
            yield x
            x,y = y, x+y

def test_if_even(seq):
    for number in seq:
        if number % 2 == 0:
            yield number

def less_than_4million(seq):
    for number in seq:
        if number > 4000000:
            break
        yield number

"""Prints answer when ran"""

print (sum(test_if_even(less_than_4million(fibonacci()))))


4613732

In [10]:
# This cell will be used for grading, leave it at the end of the notebook.

In [ ]: