-
Notifications
You must be signed in to change notification settings - Fork 0
/
0002-Even-Fibonacci-Numbers.py
38 lines (32 loc) · 1.3 KB
/
0002-Even-Fibonacci-Numbers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Even Fibonacci numbers
#
# Problem 2
# 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.
# Define function
def even_fibonacci_sum(less_than = 100):
# set the first and second numbers of the Fibonacci sequence
first_number = 1
second_number = 2
number_sequence = [first_number, second_number]
next_number = first_number + second_number
while next_number < less_than:
# add the next number to the sequence
number_sequence.append(next_number)
# compute the next number in the sequence
first_number = second_number
second_number = next_number
next_number = first_number + second_number
# create function to detect even numbers
even_numbers = lambda x: x % 2 == 0
# filter for even numbers
even_fibonacci_numbers = list(filter(even_numbers, number_sequence))
# return the sum
print("The sum of even Fibonacci numbers under", "{:,}".format(less_than), "is:\n", "{:,}".format(sum(even_fibonacci_numbers)))
even_fibonacci_sum(4000000)
# The sum of even Fibonacci numbers under 4,000,000 is:
# 4,613,732