Today I’ll be doing another Project Euler problem.
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.
There are many ways to do this problem, but I’ve chosen to create a series of functions that I can run to get Fibonacci numbers until some upper bound, and then the sum of even numbers in a list. I find that abstracting calculations like these into functions is a very easy way to make programs feel and look more organized as well as increasing reusability and convenience. A good example would be that I may need a Fibonacci sequence in a future problem, and using a function like this allows me to just paste this code into a future program and I can recall on it using
fib(max) when needed. I’m going to begin by creating a function to find the Fibonacci numbers up to some upper bound. I’ll create the function
max is the upper bound of the number we’ll be getting from the Fibonacci sequence. The best way I can come up with to create a Fibonacci sequence is to create a list and use
fib[-2] to grab the latest two numbers in the sequence. Next, I’ll add in a
while loop that iterates through the Fibonacci sequence and places the numbers into the list
fib[ ], to create the next Fibonacci number. This loop then breaks when we hit the upper bound we placed earlier. After this the function will return the newly filled list
def fib(max): fib = [1, 2] while(int(fib[-1] + fib[-2]) <= max): fib.append(int(fib[-1]+fib[-2])) return fib
Next, I need to create a function that will add the even numbers of a list together. I’ll call this function
even_sum(list) and to create it I’m going to use something new I learned called List Comprehension. You can learn more about List Comprehension here but I’ll provide a quick overview. List Comprehension allows a smaller and more efficient way to create a list by placing a
for loop inside of square brackets. We can also place operators such as
if statements inside the brackets. Using this new tool my next function will look like this:
def even_sum(list): return sum([i for i in list if i%2==0])
Now that we have both of our functions we can just combine the two and run them through each other like so:
This now returns us with the sum of all even Fibonacci numbers up until 4 million!
Thanks for reading and have a wonderful day!
I would like to give special thanks to Christian Ferko for teaching me about List Comprehension.