Before writing the Python Fibonacci generator, you should know the Generator in Python and Fibonacci series
Prerequisite:
In an earlier post, we have seen a Python generator.
As per the name “Generator”, is a function that generates the values (more than one or a series of values).
It is a sequence of numbers in which every next term is the sum of the previous two terms.
However, this logic doesn’t apply to the first two terms of the sequence. The first two terms are initialized to 1.
The Fibonacci series looks like
1, 1, 2, 3, 5, 8, 13, 21, ...
Here is a simple Python program to print the Fibonacci series…
def fibonacci(): a=0 b=1 for i in range(6): print(b) a,b= b,a+b obj = fibonacci()
Output:
1 1 2 3 5 8
In a single function call, we are printing all the Fibonacci number series.
So, instead of using the function, we can write a Python generator so that every time we call the generator it should return the next number from the Fibonacci series.
Basically, we are using yield rather than return keyword in the Fibonacci function.
Here you go…
def fibonacciGenerator(): a=0 b=1 for i in range(6): yield b a,b= b,a+b obj = fibonacciGenerator() print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj))
Output:
1 1 2 3 5 8
If you look at the above program, you can see, the generator preserves the state. When you call next time, it executes from where it had terminated.
Instead of using for loop, we are using, while conditional loop in Python. When we pass True
as an argument, while-condition always holds True.
def fibonacciGenerator(): a=0 b=1 while(True): yield b a,b= b,a+b obj = fibonacciGenerator() print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj))
Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
Now you can call fibonacciGenerator()
function as many times as you want. Every time you call it, it returns the next number from the Fibonacci series.
I have been asked to write a Python Fibonacci generator in many Python interview questions. Understand the concepts of how Generator works.
There can be many interview coding questions that can be asked on the Fibonacci series. For example, how to check if the given number is Fibonacci or not.
Any doubt? Write in the comment.