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 [100]:
# YOUR CODE HERE
fibo = [i for i in range(-30,2)]     #Takes range of numbers from -30 to 2, the reason for those numbers being that\
def sequence(x):                     #when I ran my functions, that range was the only one where I started a 1 and\
    for j in range(0,len(x)):        #ended below 4 million, but I couldn;t figure out why.
        x[j] = x[j-2] + x[j-1]
    return x

print(sequence(fibo))

def evens(x):
    if x % 2 == 0:
        return x

new = list(filter(evens, fibo))    #filters out all even numbers in the sequence

print(new)                         #prints new sequence and sum of all numbers in sequence

print(sum(new))


[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578]
[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
4613732

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

In [ ]: