Introduction
In this example we will see how to build fibonacci series using Python programming language. We will create both recursive and non-recursive function in Python programming language to build the fibonacci series.
In mathematics, the Fibonacci numbers, commonly denoted Fₙ, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, and for n > 1. Wikipedia
Prerequisites
Python 3.8.1
Non-recursive Implementation
In non-recursive implementation we will keep track of the previous, current and last previous to build the series.
def non_recur_fibo(n):
curr = 0
prev = 1
lastprev = 0
series = '0 1'
for i in range(2, n):
curr = prev + lastprev
series += ' ' + str(curr)
lastprev = prev
prev = curr
return series
Recursive Implementation
In recursive implementation we will recursively call the same function to build the series.
def recur_fibo(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return recur_fibo(n - 1) + recur_fibo(n - 2)
Testing the Program
Now we will execute the program as shown below:
n=int(input("Enter the terms: "))
print('Number of fibonacci terms in a series', n)
print('Series (non-recursive): ', non_recur_fibo(n))
print('Series (recursive): ', end = '')
for i in range(n):
print(str(recur_fibo(i)) + ' ', end = '')
In the above code snippets we are testing both non-recursive and recursive functions.
The above code snippets will give you below output:
Enter the terms: 10
Number of fibonacci terms in a series 10
Series (non-recursive): 0 1 1 2 3 5 8 13 21 34
Series (recursive): 0 1 1 2 3 5 8 13 21 34
We have given end = ' '
in the print statement to print the value or string in the same line. By default print()
function prints the string or value on a new line.
Thanks for reading.