Description of the 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:
\begin{eqnarray}
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
\end{eqnarray}
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
When the Fibonacci function is called the function asks the user to type in a number to which the Fibonacci Sequence will be developed. Of course, this is a string that must be converted to an integer to be used later in the program. In this case, we have created a while loop that repeatedly asks the user to type in a number that will be converted to an integer. If the user types characters alongside numbers then the program execution will skip the try block and jump to except block This block is activated as soon Windows detects such a problem.
Solution: Beginner Level
Before we even create a procedure for calculating the sum of even-valued terms we have to develop a procedure for generating the Fibonacci sequence. The Fibonacci sequence is a type of sequence in which each number is the sum of the two preceding ones. As stated the sequence starts from 0 and 1, the next few values of the sequence are: \begin{eqnarray} 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... \end{eqnarray} In our program, we will start by asking a user to input the value up to which the Fibonacci sequence will be developed. The value represents the length (number of elements) of the Fibonacci sequence list. This will be done using the input function and the entered number will be converted to an integer using int function. Finally, the integer type value will be assigned to a variable named terms.nterms = int(input("Enter a number to which i Fibonacci Sequence will be developed :>"))The first two elements of the Fibonacci sequence are known as 0 and 1 so we have to assign them to variable names n1 and n2. Besides these two variables the count variable must be defined which will be later used in the while loop. The list to which Fibonacci numbers will be appended has to be defined and will be assigned to the variable FibList.
n1, n2 = 0, 1The while loop will be used to fill the FibList list.
count = 0
FibList = []
while count < nterms:The while loop will be executed until count value becomes equal to nterms. Inside the while loop the nth variable is equal to the addition of n1 and n2. For the next iteration, we have to update the values of n1 and n2. So in the next iteration the count values must be updated, the value of n1 is equal to the value of n2 , and the value of n2 is equal to nth. Also the current nth value must be appended (inserted) to FibList. To provide a better understanding of the while loop see the following block of code.
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
FibList.append(nth)
n1 = 0; n2 = 1After the Fibonacci list is created we have to extract only those numbers that are even. The first step is to create an empty list which will be populated with even numbers from the Fibonacci sequence.
Iteration number 0
nth = 0+1 = 1
count = 1
n1 = n2 => 1
n2 = nth => 1
Iteration number 1
nth = n1 + n2 = 1+1 = 2
count = 2
RefinedList = []Using for loop we will find the even numbers from the sequence and store them into RefinedList. If the Fibonacci number divided by 2 is without remainder (FibListf[i]%2 == 0) then the number is append into RefinedList. Otherwise, the numbers are omitted. Finally, after the list of even valued numbers from the Fibonacci sequence is obtained we can calculate the sum using the sum function.
for i in range(len(fibList)):Output:
if FibList[i] % 2 == 0:
RefinedList.append(FibList[i])
else:
pass
print("Refined List = {}".format(RefinedList))
print("Sum(RefinedList) = {}".format(sum(RefinedList)))
Enter a number to which Fibonacci Sequence will be developed:> 10
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Refined List = [2, 8, 34]
Sum(RefinedList) = 44
Find the sum of the even-valued terms for Fibonacci sequence up to 4 million.
Now that the complete program is created we can calculate the sum of even numbers of Fibonacci sequences up to 4 million. First, we have to find the number of elements that are required to reach up to 4 million. By setting the nterms up to 32 the following Fibonacci sequence.[1, 2, 3, 5, 8, 13, 21, 34, 55,The entire output from the program written in the previous example is given below. The nterms are set up to 32.
89, 144, 233, 377, 610, 987, 1597, 2584,
4181, 6765, 10946, 17711, 28657, 46368, 75025,
121393, 196418, 317811, 514229,
832040, 1346269, 2178309, 3524578]
Enter a number to which Fibonacci Sequence will be developed:> 32
[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]
Refined List = [2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
Sum(RefinedList) = 4613732
Solution: Intermediate Level
Using the previous solution (beginner level) we will create a code for the program "Even Fibonacci Numbers" using Python functions. From the previous code, we will create two functions i.e. Fibonacci function for creating a list of Fibonacci numbers and a function for summing even Fibonacci numbers.When the Fibonacci function is called the function asks the user to type in a number to which the Fibonacci Sequence will be developed. Of course, this is a string that must be converted to an integer to be used later in the program. In this case, we have created a while loop that repeatedly asks the user to type in a number that will be converted to an integer. If the user types characters alongside numbers then the program execution will skip the try block and jump to except block This block is activated as soon Windows detects such a problem.
def Fibonacci():
while True:
try:
nterms = int(input("Enter a number to which Fibonacci Sequence will be developed:>"))
break
except ValueError:
print("Invalid input. Please try again.")
continue
n1, n2 = 0,1
count = 0
FibList = []
while count < nterms:
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
FibList.append(nth)
print("Fibonacci sequence = {}".format(FibList))
return FibList
def SumEven(FList):
RefinedList = []
for i in range(len(FList)):
if FList[i]%2 == 0:
RefinedList.append(FList[i])
else: pass
print("Refined List = {}".format(RefinedList))
print("Sum Refined List = {}".format(sum(RefinedList)))
return RefinedList
FibonList = Fibonacci()
RefList = SumEven(FibonList)
Solution: Advanced Level
At this level, we will create a class named EvenFibonSeq that will calculate the sum of the Even number Fibonacci sequence. For this case, we will re-use some of the code from the intermediate and beginner level. In this class, there will be three methods i.e. __init__ method to initialize attributes each time the object of the class is created, FibSequence method for creating Fibonacci sequence up to predefined number by the user, and SumEven method to find the even Fibonacci sequence numbers and sum those numbers. The first step is to define the class:class EvenFibonSeq():The second step is to define the __init__ function that will when a new object is created, initialize the following attributes of that object:
#Class body
- nterms - variable used to define limit in Fibonacci sequence dvelopment
- n1,n2 - variables to which two values are assigned 0 and 1. These two values are the initial values of the Fibonacci sequence.
- count - variable to which 0 value is assigned. This variable is used in the while loop to develop the sequence.
- FibList = [] - an empty list to which all values from predefined maximum value by nterms variable value will be stored
- RefinedList = [] - a empty list which will be used to store even numbers from Fibonacci sequence.
def __init__(self):As stated previously the FibSeqence method is used to generate Fibonacci sequence up to nterms value. The method will require all attributes initialized by the __init__ function except for the RefinedList. The FibSequence() method starts with a while loop in which newly created values are stored in the FibList list. After the list is generated the list is shown using the print function and the return value of this method is the FibList list.
while True:
try:
self.nterms = int(input("Enter a number to which Fibonacci Sequence will be developed:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
self.n1, self.n2 = 0,1
self.count = 0
self.FibList = []
self.RefinedList = []
def FibSequence(self, nterms, n1, n2, count, FibList):Now that the method for creating the list of the Fibonacci sequence is created we have to develop a method for creating a list with only even numbers from the Fibonacci sequence. In this method, a FibList will be traversed and modulo will be calculated (FList[i]%2). If the value of this operation is equal to 0 (no remainder) then the number for FibList is the even number and will be appended to the RefinedList. After even numbers were collected the list will be summed up to determine the sum of the even numbers from the Fibonacci sequence.
while count < nterms:
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
FibList.append(nth)
print("Fibonacci sequence = {}".format(FibList))
return FibList
def SumEven(self, FList, RefinedList):The entire class is given below.
for i in range(len(FList)):
if FList[i]%2 == 0:
RefinedList.append(FList[i])
else: pass
print("Refined List = {}".format(RefinedList))
print("Sum Refined List = {}".format(sum(RefinedList)))
return RefinedList
class class EvenFibonSeq():To test the program we will create an object as an instance of the class EvenFibonSeq.
def __init__(self):
while True:
try:
self.nterms = int(input("Enter a number to which Fibonacci Sequence will be developed:> "))
break
except ValueError:
print("Invalid input. Please try again.")
continue
self.n1, self.n2 = 0,1
self.count = 0
self.FibList = []
self.RefinedList = []
def FibSequence(self, nterms, n1, n2, count, FibList):
while count < nterms:
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
FibList.append(nth)
print("Fibonacci sequence = {}".format(FibList))
return FibList
def SumEven(self, FList, RefinedList):
for i in range(len(FList)):
if FList[i]%2 == 0:
RefinedList.append(FList[i])
else: pass
print("Refined List = {}".format(RefinedList))
print("Sum Refined List = {}".format(sum(RefinedList)))
return RefinedList
test = EvenFibonSeq()With previous object creation, we have initialized the following attributes: nterms, n1, n2, count, FibList, and Refined List. The next step is to obtain the Fibonacci sequence list using the FibSequence method. To obtain this list it is important to provide the method FibSequence with test attributes (all except the RefinedList).
Seq = test.FibSequence(test.nterms, test.n1, test.n2, test.count, test.FibList)Finally, we have to find the even numbers from the Fibonacci sequence list and sum them to obtain a result.
res = test.seven(Seq, test.RefinedList)Output:
Enter a number to which Fibonacci Sequence will be developed:> 32
Fibonacci sequence = [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]
Refined List = [2, 8, 34, 144, 610, 2584,
10946, 46368, 196418, 832040, 3524578]
Sum Refined List = 4613732