
Fibonacci Series in Python is a most sought-after intermediate-level programming question. It is often asked during many technical interviews. A Fibonacci number is a sequence of numbers in which every number in the sequence is added to the two previous numbers to find the current number. Let us read this article to write a program for printing the Fibonacci series in Python.
Using Binet’s Formula we can calculate the Fibonacci series in Python directly using mathematical expression using the golden ratio.
| Fibonacci Series in Python (Binet’s Formula) |
| import math def fibonacci(n): phi = (1 + math.sqrt(5)) / 2 psi = (1 - math.sqrt(5)) / 2 return int((phi**n - psi**n) / math.sqrt(5)) |
| Fibonacci Series in Python using Loop |
| def fibonacci_series(n): a, b = 0, 1 for _ in range(n): print(a, end=" ") a, b = b, a + b Fibonacci_series(10) |
Output
This function fibonnaci_series() takes two variables and assigns them with values 0 and 1. Now taking a for loop we keep on reassigning the value of a and b by assigning the value of b to a and assigning a+b to b. However, this function can only find the Fibonacci till a specified series.
| Fibonacci Series in Python using Recursion |
| def fibonacci_recursive(n): if n <= 1: return n else: return fibonacci_recursive(n-1) + fibonacci_recursive(n-2) def print_fibonacci_series(n): for i in range(n): print(fibonacci_recursive(i), end=" ") # Print Fibonacci series up to 10 numbers using recursion print_fibonacci_series(10) |
Output
Here using the recursion function fibonacci_recursive() function we first take a base case when n is less than 1 and return the value of n. If n is greater than 1 then we call the sum of fibonacci_recursive(n-1) and fibonacci_recursive(n-2) repeatedly until the base case is reached.
| Fibonacci Series in Python using Dynamic Programming |
| memo = {0: 0, 1: 1} def fibonacci_memoization(n): if n in memo: return memo[n] memo[n] = fibonacci_memoization(n-1) + fibonacci_memoization(n-2) return memo[n] def print_fibonacci_series(n): for i in range(n): print(fibonacci_memoization(i), end=" ") # Print Fibonacci series up to 10 numbers using memoization print_fibonacci_series(5) |
Output
Here, using dynamic programming we store the value of 0 and 1 first in a variable memo. We created a function fibonacci_memoization() to find and print the Fibonacci series in Python using a dynamic programming approach. The time complexity of this approach is O(n) where n is the number.
| Fibonacci Series in Python using Backtracking |
| def fibonacci(n, memo={}): if n <= 0: return 0 elif n == 1: return 1 elif n in memo: return memo[n] else: memo[n] = fibonacci(n-1) + fibonacci(n-2) return memo[n] print(fibonacci(7)) |