Attempt at problem 2. Not my first rodeo, but enjoyable regardless.
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.
https://projecteuler.net/problem=2
import pprint
pp = pprint.PrettyPrinter(indent=4, compact=True)
# The first thing that comes to mind to solve this is to google the fibonacci algorithm
# https://stackoverflow.com/questions/18172257/efficient-calculation-of-fibonacci-series
# will give us the function needed to get started
def fib_to(n):
fibs = [0, 1]
for i in range(2, n+1):
fibs.append(fibs[-1] + fibs[-2])
return fibs
# Generate list of fibbonaci numbers
fib_list_to_50 = fib_to(50)
pp.pprint(fib_list_to_50)
OUTPUT:
[ 0, 1, 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, 5702887, 9227465, 14930352,
24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049,
12586269025]
# Remove the first two numbers
fib_list_to_50_clean = fib_list_to_50[2:]
fib_list_even = list(filter(lambda x : x%2 == 0, fib_list_to_50_clean))
fib_list_less_than_4mil = list(filter(lambda x : x < 4000000, fib_list_even))
pp.pprint(fib_list_less_than_4mil)
OUTPUT:
[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
sum(fib_list_less_than_4mil)
OUTPUT:
4613732