Solution Review: Corresponding Fibonacci Number
This review provides a detailed analysis of the ways to find the corresponding element at a given index in the Fibonacci series.
We'll cover the following
Solution #1: Iterative Method
def fibonacci(testVariable):fn0 = 0fn1 = 1for i in range(0, testVariable):temp = fn0 + fn1# Setting variables for next iterationfn0 = fn1fn1 = tempreturn fn0# Driver CodetestVariable = 7print(fibonacci(testVariable))
Explanation
In the iterative method, we keep track of the two previous elements using the variables fn0
and fn1
.
Initially, the values of the two variables are:
fn0 = 0
fn1 = 1
However, in each iteration, the values are updated in the following way:
Solution #2: Recursive Method
def fibonacci(testVariable):# Base Caseif testVariable <= 1 :return testVariable# Recursive Casereturn(fibonacci(testVariable - 1) + fibonacci(testVariable - 2))# Driver CodetestVariable = 7print(fibonacci(testVariable))
Explanation:
In the code above, the function fibonacci()
is a recursive function as it calls itself in the function body.
The base case of the function (line number 3) deals with the two initial values, i.e, for index the value is and for the index, the value is :
if testVariable <= 1 :
return testVariable
However, for the recursive case, the parent function calls two instances of itself recursively with and . The input arguments correspond to the equation for finding a general term in the Fibonacci sequence.
n n-2n-1
Let’s look at the code flow:
In the next lesson, we have a short quiz for you to test your concepts.