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.
Initialize total to zero and start fibonacci sequence with 0 and 1
In [2]:
total = 0
fib = [0,1]
Using a while loop, add the last two numbers in the fibonacci sequence until the last number reaches 3,000,000.
I did not use 4,000,000 because then the sum of the last two numbers exceed 4,000,000.
In [3]:
while fib[-1] < 3000000:
fib.append(fib[-1] + fib[-2])
Using a lambda and filter, print the sum of the even-valued terms of the fibonacci sequence
In [4]:
print(sum(filter(lambda x: x % 2, fib)))
Success! (Checked answer by hand)
In [ ]:
# This cell will be used for grading, leave it at the end of the notebook.