"Even Fibonacci number"
The Fibonacci sequence terms are the sum of the previous two terms. If the first two terms are 1, 2, then the first 10 terms are:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of even-valued terms with a sequence term value of 4 million or less.
It is not possible to define a list of infinite length in common programming languages. However, since functional languages have a mechanism called lazy evaluation and an infinite list can be easily created, it is a functional method to define the Fibonacci number sequence as an infinite list. Strictly speaking, you can't create an infinite list in Python, but you can use a generator to represent something close to an infinite list.
A normal function returns a value with return, but a generator function returns a value with yield.
Generator function
def generate():
n = 1
yield n
n += 1
yield n
n += 1
yield n
Executing the generator function creates a generator object.
>>> generator = generate()
>>> for i in generator:
... print(i)
...
1
2
3
When called the first time, it returns a value in the first yield and breaks there. When called the second time, processing starts from the point where it was interrupted last time, returns a value in the next yield, and interrupts there. The difference from return is that yield does not leave the function even if the value is returned.
The itertools module provides functions for use in functional programming. This problem uses the takewhile function to retrieve only elements less than or equal to 4000000. The takewhile function creates an iterator that returns elements only while the conditions are met. Unlike the filter function, if the condition is not met even once, the subsequent elements will not be returned.
>>> from itertools import takewhile
>>> x = takewhile(lambda n: n < 10, range(100))
>>> list(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# -*- coding: UTF-8 -*-
from itertools import takewhile
def generateFibonacci():
'''Generator function to generate Fibonacci sequence'''
n1, n2 = 1, 2
while True:
yield n1
n1, n2 = n2, n1 + n2
#Create a Fibonacci sequence with a generator function.
fibonacci_sequence = generateFibonacci()
#Use the takewhile function to narrow down the range to elements of 4000000 or less.
fibonaccis = takewhile(lambda n: n <= 4000000, fibonacci_sequence)
#Extract only even numbers with the filter function.
even_fibonaccis = filter(lambda n: n % 2 == 0, fibonaccis)
answer = sum(even_fibonaccis)
print(answer)
Recommended Posts