# 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 [2]:

def fib(max_num):
sequence = []
x = 0
while x >= 0:
if len(sequence) == 0 or len(sequence) == 1: #start fibonnaci sequence with 0 and 1
sequence.append(x)
x += 1
elif sequence[x-1] >= max_num: # since we are incrementing x by 1 each time, if the number at x-1 is greater than "max-num" (in this case 4 million) we remove it and stop the loop
sequence.remove(sequence[x-1])
break
else:
sequence.append(sequence[x-1] + sequence[x-2]) # after we have 0, 1, we make the rest of the fibonnaci numbers by adding the two before it
x += 1

return sequence # this function will return the sequence

#--- summing it up: the first function takes a max number (4 million) and generated a fibonnaci sequence with values that do not exceed your max number

def fib_sum(sequence): # this function takes a fibonnaci sequence (like the one generated in the function above)
even_fib = []
for numbers in sequence:
if numbers % 2 == 0: # if the numbers in the sequence divided 2 has a remained of zero, it's even
even_fib.append(numbers) # and is appened to my list "even_fib"
return sum(even_fib) # the function then returns the sum of the list

print(fib_sum(fib(4000000)))

``````
``````

4613732

``````
``````

In [14]:

# This cell will be used for grading, leave it at the end of the notebook.

``````
``````

In [ ]:

``````
``````

In [ ]:

``````