
If you're invited for a coding interview, one of the classic questions you might be asked is how would you code a Fibonacci series? For obvious reasons, you'll first need to know what's a Fibonacci series before you can implement the solution. Then you'll need to decide which language you will use to implement the solution. Let's first with a simple definition of the Fibonacci series and later we will focus on its implementation using Python.
The Fibonacci Sequence (Fn) is the series of numbers such that each number is calculated by adding the sum of the two numbers before it, with the first two terms being 0 and 1.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233...
From a mathematical standpoint, the Fibonacci Sequence is defined by a recurrence relation and is defined using the following rule.
where:
So let's implement the Fibonacci Sequence using the recursive formula in Python. Before you dive in you'll need to understand the following programming concepts in Python.
def fib_recursive(n):
if n <= 1:
return n
else:
return (fib_recursive(n-1) + fib_recursive(n-2))
no_terms = 14
#check n<0
if no_terms < 0:
print("Invalid input, please enter a positive integer.")
else:
print("The first 14 terms of Fibionacci Sequence are as follows." )
for i in range(no_terms):
print(fib_recursive(i))
The first 14 terms of Fibionacci Sequence are as follows.
0
1
1
2
3
5
8
13
21
34
55
89
144
233Keep the momentum going in preparation for your interview and check out my article on the four pillars of Object-Oriented Programming here.
Kadian Davis-Owusu