Fibonacci series in python

Fibonacci Series in Python

Fibonacci Series in Python

Fibonacci series can be explained as a sequence of numbers where the numbers can be formed by adding the previous two numbers. It starts from 1 and can go upto a sequence of any finite set of numbers. It is 1, 1, 2, 3, 5, 8, 13, 21. etc. As python is designed based on object-oriented concepts, multiple conditional statements can be used to design logic for the Fibonacci series. Three types of usual methods for implementing the Fibonacci series are ‘using python generators‘, ‘using recursion’, and ‘using for loop’.

Web development, programming languages, Software testing & others

For Example:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ..so on

Looking at the above, one would have got a certain idea about what we are talking about.

Читайте также:  How to use date in java

However, In terms of mathematical rule, it can be written as:

fibonacci python1

Where nth number is the sum of the number at places (n-1) and (n-2). When it comes to implementing the Fibonacci series, there could be a number of coding languages through which it could be done.

However, Python is a widely used language nowadays. Let’s see the implementation of the Fibonacci series through Python. One should be aware of basic conditioning statements like the loop, if-else, while loop, etc., in Python before proceeding here. If not, it would be great if one can revise it and then take up the coming content. For demo purpose, I am using spyder, an IDE for the Python programming language. One can use any other IDE or Ipython notebooks as well for the execution of the Python programs.

Fibonacci Series in Python

Let’s see the implementation of Fibonacci number and Series considering 1 st two elements of Fibonacci are 0 and 1:

However, you can tweak the function of Fibonacci as per your requirement but see the basics first and gradually move on to others.

Python Code for finding nth Fibonacci Number

def Fibonacci_num(m): u = 0 v = 1 if m < 0: print("Incorrect input entered") elif m == 0: return u elif m == 1: return v else: for i in range(2,m): c = u + v u = v v = c return v

fibonacci python2

fibonacci python3

As one can see, the Fibonacci number at 9 th place would be 21, and at 11 th place would be 55.

  • Here “fibonacci_num” is a function defined, which takes care of finding the Fibonacci number with the help of certain conditions. This function can be called by specifying any position.

Now let’s see how one can print series till the position mentioned:

fibonacci python4

fibonacci python5

One can notice the start of Fibonacci numbers is defined as 0 and 1.

  • If someone wants to define their own starting terms, that can also be done in the same way by tweaking n1 and n2. Here is the example for that:

Let’s say now we want our starting terms be: n1 = 3, n2 = 5

Fibonacci Series in Python 6

So here, your 4 th term position (user input is taken) will be decided based on your starting terms.

Methods Through which Fibonacci Series can be Generated

Below are the three methods through which the Fibonacci series can be generated:

1. Through Generators

def fibo(num): a,b = 0, 1 for i in xrange(0, num): yield "<>:: <>".format(i + 1,a) a, b = b, a + b for item in fibo(10): print item

Fibonacci Series in Python7

This method is referred to as “generator” because the function xrange is a generator of the numbers between 0 and num, and yield is the generator for formatted output.

Here is What xrange does for you:

fibonacci python8

Here Fibonacci series has been defined in the form of function, inside which for loop, xrange and yield function takes care of the output.

2. Through for loop

u, v = 0, 1 for i in xrange(0, 10): print u u, v = v, u + v

Fibonacci Series in Python 9

As one can see, a simple for loop has been used to print the Fibonacci series between 0 to 10. Inside for loop, new values have been assigned to the variables. U and v are the default initial values of Fibonacci that have been set to 0 and 1, respectively.

As for the loop progresses to run, the new u value is the old v value, whereas the new v value is the sum of old values of u and v. This continues till the end of range values.

3. Through Recursion

#Through recursion def fibonacci_ser(m): if(m 

Fibonacci Series in Python10

  • The function “fibonacci_ser” is making the call to itself to print the Fibonacci series.
  • And hence the method has got its name “recursion”.

Steps Followed here:

  1. Here the user has been asked to input the place till which the Fibonacci series needs to be printed.
  2. Number passes through the function “fibonacci_ser”.
  3. The condition gets checked if the length provided is less than 1 or not. If yes, the result is given immediately.
  4. However, if the length is greater than 1, recursive calls are made to “fibonacci_ser” with arguments having length lesser than 1 and 2, i.e. fibonacci_ser(m-1) and fibonacci_ser(m-2).
  5. Hence, recursion gives the desired output and print it.
  • So, in short, We discussed Three ways for displaying the Fibonacci series.
  • Through for loop, through generators and through recursion.

All Three Python Code’s Summarized

Below are the three python code:

1. Through Generators

def fibo(num): a,b = 0, 1 for i in xrange(0, num): yield "<>:: <>".format(i + 1,a) a, b = b, a + b for item in fibo(10): print item

2. Through for loop

u, v = 0, 1 for i in xrange(0, 10): print u u, v = v, u + v

3. Through Recursion

Summarized above are all procedures; one needs to practice to get a good grip on all.

Fibonacci Series in Python 11

Conclusion

Going through the above content of Fibonacci, one would have got a crystal clear understanding of Fibonacci numbers and series, specialized with python. Once one gets comfortable with the Fibonacci series’s logic, generating another series, working with other numbers, and various methods will now be a cakewalk for you. A logical approach is the only way to excel in this.

This is a guide to Fibonacci Series in Python. Here we discuss Fibonacci numbers and series, specialized with python, generating another series, working with other numbers, and various methods. You can also go through our other related articles to learn more –

Источник

Python Program to Print Fibonacci Series

Python Certification Course: Master the essentials

The Fibonacci numbers, abbreviated as Fn in mathematics, comprise a Fibonacci sequence in which each number is the sum of the two preceding ones. The series usually begins with 0 and 1, while some authors skip the first two terms and begin with 1 and 1 or 1 and 2. The following are the first few values in the sequence, starting with 0 and 1 : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144.

What is Fibonacci Series?

We can define the Fibonacci series as a series of numbers that start from 0 & 1, and the next number can be generated by adding the last two preceding numbers.

Fibonacci Series Logic in Python

Fibonacci series starts with 0 and 1 , so we consider these as the default values of the series.

The following number will be an addition of the last two numbers.

fibonacci series logic in python

As you can see in the above diagram, The Fibonacci series started with 0 and 1 currently, which are the last two numbers and then by adding these values, we got 1. Now the last two values are (1,1). By adding them, we got 2. Now the last two numbers are (1,2), we add them to get the following number of the Fibonacci series, and It is done until the number of terms you want.

Fibonacci Series Formula in Python

fibonacci series formula in python

So here, term 7 is called x7, which is equal to 13,

From the above diagram we can write the formula as: Xn = Xn-1 + Xn-2

Implementing the Fibonacci Series in Python

In the implementation of the Fibonacci series, we are going to see the following points:

  • Fibonacci series in python using recursion
  • Fibonacci series in python using dynamic programming
  • Fibonacci series in python – space-optimized
  • Fibonacci series in python using while loop

Fibonacci series in python using Recursion

Any function calling itself is called Recursion. Using a recursive algorithm on specific problems is relatively easy rather than an iterative approach. But in this case, using recursion in the Fibonacci series is not a good idea because it takes exponential time complexity.

Let’s see how to print the Fibonacci series till the nth term.

Constraint: n>=1.

Python Code – Recursion

Output:

From the diagram below, we can see there is a lot of repetition of the functions. This means our program has calculated the same thing many times, which consumes too much time & space

Time Complexity: O(2^n)

Space Complexity: O(n) (Max depth of the recursion tree)

Let’s take an example. Suppose we have passed n = 7 to our function fib(7). Now we have to calculate for the last two values that is fib(7-1) + fib(7-2), which is fib(6) + fib(5), but when we calculate for fib(6), again fib(5) will be calculated as you can see in the below diagram.

recursion in python fibonacci series

''

So, it’s better to avoid this recursive approach in the Fibonacci series program.

Fibonacci series in python using dynamic programming

Dynamic Programming is an algorithmic technique that solves problems by breaking them into subproblems and saves the result of these subproblems so that we do not have to re-compute them when needed.

We can check if the subproblem is already solved, and then we can directly access the result and use it. It saves computation time.

Python Code – Dynamic programming

Output:

In the above code, we have overcome the problem of repeated work done By storing subproblems results into a list named ‘fib_series’.

We have calculated the following Fibonacci series number and stored it in the ‘next_number’ variable, stored in the fib_series list To remember the result.

Time Complexity: O(n)

Space Complexity: O(n)

Here, we have optimized the time complexity by dynamic programming, but still, space complexity is not optimized.

Fibonacci series in python – space optimized

Now let’s optimize the space complexity.

Python Code – Space Optimized

Output:

In the above code, we have not taken any extra space memory. We have printed the Fibonacci series using a for loop by which we can say it is space-optimized.

Here the space complexity is O(1) & time complexity O(n). We have separately printed the first two default values, which are 0 & 1 and with the help of these values, we have calculated the next sequence of the Fibonacci series.

Fibonacci series in python using while loop

Here, the Fibonacci series using a while loop is implemented.

Python Code:

Output:

Time Complexity: O(n)

Space Complexity: O(1)

So, we have discussed four methods to print the Fibonacci series in python. It is totally up to you which method you should use. If complexity does not matter, then you can use a recursive approach. Else, you can use a dynamic programming approach.

Some of the applications of the Fibonacci series:

1. Fibonacci search – It can be defined as a technique which is based on the comparison that uses Fibonacci numbers to search an element in a sorted array.

2. Golden Ratio – Fibonacci series helps to understand the golden ratio. The Golden ratio is derived from the Fibonacci series. The golden ratio describes a predictable pattern on everything from atoms to giant stars in space.

Conclusion

  • Fibonacci Series is a sequence generated such that the Nth term of the sequence is formed by addition of (N-1)-th term and (N-2)-th term.Starting from 0 and 1.
  • Applications of Fibonacci Series are Fibonacci Search and Golden Ratio.

Read More:

Источник

Оцените статью