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 is_even_sum(x): #created this funtion at Dr. Granger's suggestion rather than having it in fibonnaci function
even=0 #starts sum at 0
for i in x: #iterates through numbers and if number is even adds to total
if i%2==0:
even+=i
return even #returns the total of even numbers
In [3]:
print(is_even_sum([1,2,3,4,5,])) #test for is even function
In [10]:
def fibonacci(x,y): #Decides what numbers to start the Fibonnaci sequence at- i.e 0,1
fibona=[x,y] #starts list with the numbers of choosing
fib=0 #assigns fib so it can be referenced later (could be any number under 4 million I chose 0)
while fib < 4*10**6:
fib=x+y #reassigns fib
x=y
y=fib #reassigns x and y
if fib < 4*10**6: ##Without this statement function returns a number that is one iteration past the limit
fibona.append(fib)#however without it the sum is unaffected for this problem because it is an odd number
return fibona
Below tests that numbers in fibona don't exceed four million. The final number did exceed four million untill I added the if statement in fibonacci(). This was because fib stored the previous number and as long as that was under 4 million it would still assign and append one more value of fib.
In [11]:
print( fibonacci(0,1))
In [9]:
print(is_even_sum((fibonacci(0,1)))) #sums the even values in series created by fibonacci()
In [5]:
# This cell will be used for grading, leave it at the end of the notebook.