"""
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.
"""


import itertools


def get_fibonacci_generator():
    # Normally, fibonacci sequences start with 1, 1, 2, 3, 5, etc.
    # This omits the first "1" but that's okay since 1 is odd.
    first_previous_value = 0
    second_previous_value = 1
    for _ in itertools.count():
        first_previous_value, second_previous_value = second_previous_value, first_previous_value + second_previous_value
        yield second_previous_value


def get_even_fibonacci_sum(maximum):
    generator = get_fibonacci_generator()
    fibonacci_sum = 0
    for _ in itertools.count():
        fibonacci = next(generator)
        if fibonacci > maximum:
            break
        if fibonacci % 2 == 1:
            continue
        fibonacci_sum += fibonacci

    return fibonacci_sum


answer = get_even_fibonacci_sum(4 * 10 ** 6)
