Solution Review : Compute nth Fibonacci Number
Explore how to implement a recursive function in Python to compute the nth Fibonacci number. Understand the base cases and recursive steps that define the Fibonacci sequence, and practice coding this solution to solidify your grasp of Python recursion.
We'll cover the following...
We'll cover the following...
Solution: Use Recursion
The Fibonacci sequence is obtained by adding the previous two consecutive terms; they are defined by the sequence,
fibonacci(0) = 0 # base case
fibonacci(1) = 1
fibonacci(n) = fibonacci(n – 1) + fibonacci(n – 2) for n >= 2 # recursive case
For example ,
0,1,1,2,3,5,8,......
if n=2, f(n)=3
The following illustration explains the concept by calculating the fourth Fibonacci number.
The following python code demonstrates how to find the nth fibonacci number:
Let’s move on to the next problem.