Key focus: Learn to generate Fibonacci sequence using Python. Python 3 is used in this tutorial. Fibonacci series is a sequence of numbers 0,1,1,2,3,5,8,13,…
Let’s digress a bit from signal processing and brush up basic some concepts in python programming.
Why python?
Python is an incredibly versatile programming language that is used for everything from machine learning, artificial intelligence, embedded programming, etc.., It is an open source programming language that comes with a vast repertoire of specialized libraries. A lot of top universities – like MIT, Stanford and Berkeley – have switch to Python programming for their undergraduate courses, so it will likely remain popular in the future. It has consistently maintained the first place, for several years in a row, in IEEE spectrum’s list of top languages↗.
Fibonacci sequence in python
Let’s take up the famous example for coding a program in Python that generates a Fibonacci sequence↗. Mathematically, a Fibonacci sequence is represented in recursive form as
This can be directly translated in Python version 3 command line as
>>> def F(n): ... if n == 0: return 0 ... elif n == 1: return 1 ... else: return F(n-1)+F(n-2) >>> F(1) 1 >>> F(10) 55
Alternatively, we can use while loop to generate Fibonacci numbers. The following generator function↗ returns an iterator↗.
>>> def F(): ... a, b = 0, 1 ... while a < 100: #generate result upto 100 ... yield a ... a, b = b, a+b
The program results in an iterable object that represents a stream of data. The elements of the object can be obtained one by one as
>>> x = F() #calling the function returns iterable object
>>> next(x)
0
>>> next(x)
1
>>> next(x)
1
>>> next(x)
2
... so on
The resulting iterable object can be materialized as a list↗ or a tuple↗
>>> list(F()) #Function returns iterable object, print it as list
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> tuple(F()) #Function returns iterable object, print it as tuple
(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
Rate this article:
Articles in this series
Books by the author