How to implement the Fibonacci sequence in Python
The Fibonacci Sequence is the series of numbers:
The series starts with and as the first two numbers in the series. The next number in the series is found by summing the two numbers before it.
For example:
- The third number in the sequence, , is found by adding the two numbers before it .
- The fourth number in the sequence, , is found by adding the two numbers before it .
Implementing the Fibonacci Sequence
Fibonacci Sequence can be implemented both iteratively and recursively in Python.
For both examples, try changing the value of the argument passed to the function to print out more numbers in the sequence.
Iterative implementation
def fib(number_of_terms):counter = 0first = 0second = 1temp = 0while counter <= number_of_terms:print(first)temp = first + secondfirst = secondsecond = tempcounter = counter + 1# Driver Codefib(10)
In the above implementation, The code prints the first value on each iteration of the loop. Each iteration calculates the next value by summing the previous two values and then updates the values of first and second. The time complexity of the above iterative implementation is .
Recursive Implementation
def fib(term):if term <= 1:return (term)else:return (fib(term-1) + fib(term-2))# Change this value to adjust the number of terms in the sequence.number_of_terms = 10for i in range(number_of_terms):print(fib(i))
The above program computes the Fibonacci value by calling itself with a lesser value several times. The termination condition for this is reached when term == 0 and term == 1. The time complexity for this solution is .
Free Resources