Use Python to implement the Fibonacci function, pythonfibonacci

Source: Internet
Author: User

Use Python to implement the Fibonacci function, pythonfibonacci

The onacci Fibonacci series is simple. It is a recursion. It may be used to learn any programming language.

Recently, I was playing Python. After reading Learning Python and Core Python, I accidentally found a post on the Internet, which is interesting for Python programmers. So I plan to follow the same article. The post used more than 10 methods to complete a factorial function. Here I will write a function of Fibonacci in nine different styles.

The requirement is very simple. Input n, output n Fibonacci numbers, and n is a positive integer.

The following are nine different styles:

1) The Python programmer who writes the program for the first time:

def fib(n):  return nth fibonacci number

Note:
For the first time, the person who writes a program often follows the syntax of the human language rather than the syntax of the programming language. For example, he wrote the first program to judge the leap year, it is written directly as follows: If year is a leap year, the output year is a leap year. Otherwise, year is not a leap year.

2) C programmers who have just learned Python:

def fib(n):#{ if n<=2 :  return 1; else:  return fib(n-1)+fib(n-2);#}

Note:
When I first came into contact with Python, I was very uncomfortable using indentation instead of braces to divide program blocks. In addition, there was no Terminator behind each statement, therefore, the first thing to do after writing a Python function is to annotate the braces and add the missing colon.

3) lazy Python programmers:

def fib(n):  return 1 and n<=2 or fib(n-1)+fib(n-2)

Note:
After reading Learning Python, do you know that Python does not have a ternary operator ?, However, given that the bool value in Python is special (a bit like C, non-zero is true, non-empty is true), and the Python logical statement also supports Short-Circuit (Short-Circuit Evaluation) can this write a copy? Statement.

4) more lazy Python programmers:

 fib=lambda n:1 if n<=2 else fib(n-1)+fib(n-2)

Note:
Lambda keywords I have used in C # And Scheme. lambda in Python is easier than C # And is similar to Scheme usage, so I quickly adapted to it. This method is often used when using Python Shell to declare small functions.

5) Python programmers who have just finished learning the data structure:

def fib(n): x,y=0,1 while(n):  x,y,n=y,x+y,n-1 return x

Note:
The previous Fibonacci functions are implemented by tree recursion. Even if you want to learn some algorithms, you should know that this recursion is inefficient. Here, changing from tree recursion to corresponding iteration can greatly improve the efficiency.
The assignment of tuples in Python is a favorite feature, which can simplify the Code a lot. For example, the previous tmp = a; a = B; B = tmp; can be directly implemented using a, B = B, a, which is concise and clear.

6) Python programmers who are taking the SiC program:

def fib(n):  def fib_iter(n,x,y):   if n==0 : return x   else : return fib_iter(n-1,y,x+y)  return fib_iter(n,0,1)

Note:
Here I use Tail-recursion, a common method in Scheme. There are no iterations in Scheme, but they can be simulated using the invariant and tail recursion to achieve the same effect. But I still don't know whether Python has optimized tail recursion. I will check it later.
PS: I can see at a glance that this program is actually an example in Chapter 1.

7) a clever Python programmer:

fib=lambda n,x=0,y=1:x if not n else f(n-1,y,x+y)

Note:
Similar to the above example, the basic logic is tail recursion. The main difference is that the default parameters and ternary operators provided by Python are used to simplify the code to one line. As for the default parameters, students who have learned C ++ know this stuff. C #4.0 also introduces this stuff.

8) Python programmers who have just finished linear algebra:

def fib(n): def m1(a,b):  m=[[],[]]  m[0].append(a[0][0]*b[0][0]+a[0][1]*b[1][0])  m[0].append(a[0][0]*b[0][1]+a[0][1]*b[1][1])  m[1].append(a[1][0]*b[0][0]+a[1][1]*b[1][0])  m[1].append(a[1][0]*b[1][0]+a[1][1]*b[1][1])  return m def m2(a,b):  m=[]  m.append(a[0][0]*b[0][0]+a[0][1]*b[1][0])  m.append(a[1][0]*b[0][0]+a[1][1]*b[1][0])  return m return m2(reduce(m1,[[[0,1],[1,1]] for i in range(n)]),[[0],[1]])[0]

Note:
This code is not as clear as the previous code, so first introduce the principle (requires a little linear algebra knowledge ):
First, let's take a look at the previous version of the Fibonacci function. It is easy to find that there is a transformation: y-> x, x + y-> y. For another angle, it is [x, y]-> [y, x + y].
Here, I declare a binary vector [x, y] T, which gets [y, x + y] T through a transformation, it is easy to obtain the transformation matrix [1, 0], [1, 1], that is, [[1, 0], [1, 1] * [x, y] T = [y, x + y] T
Make the binary matrix A = [[], [], and the binary vector x = [] T. It is easy to know that the result of Ax is the next Fibonacci value, that is:
Ax = [fib (1), fib (2)] T
There are also:
Ax = [fib (2), fib (3)] T
..................
And so on, you can get:

Aⁿx=[fib(n),fib(n-1)]T

That is to say, we can perform n A transformations on the binary vector [0, 1] T to obtain [fib (n), fib (n + 1)] T and then obtain fib (n ).

Here I have defined A multiplication function m1 of A binary matrix, and A transformation m2 on A binary vector. Then, we can use the reduce operation to complete A concatenation operation to get A between x, finally, fib (n) is obtained ).

9) Python programmers preparing to participate in ACM competitions:

 def fib(n): lhm=[[0,1],[1,1]] rhm=[[0],[1]] em=[[1,0],[0,1]] #multiply two matrixes def matrix_mul(lhm,rhm):  #initialize an empty matrix filled with zero  result=[[0 for i in range(len(rhm[0]))] for j in range(len(rhm))]  #multiply loop  for i in range(len(lhm)):   for j in range(len(rhm[0])):    for k in range(len(rhm)):     result[i][j]+=lhm[i][k]*rhm[k][j]  return result  def matrix_square(mat):  return matrix_mul(mat,mat) #quick transform def fib_iter(mat,n):  if not n:   return em  elif(n%2):   return matrix_mul(mat,fib_iter(mat,n-1))  else:   return matrix_square(fib_iter(mat,n/2)) return matrix_mul(fib_iter(lhm,n),rhm)[0][0]

Note:

It is easier to understand this version after reading the previous fib function. This version also uses binary transformation to calculate fib (n ). However, the difference is that the complexity of this version is lgn, while the previous version is linear.

The difference in this version is that it defines a matrix to quickly evaluate the power operation of fib_iter. The principle is very simple. It can be used to quickly evaluate the power of a natural number, so I will not talk about it here.

PS: although the ACM version is used, I have never been involved in it. After all, my own algorithms are too watery and that stuff is too high-end ...... Only here YY bird ~

In python, the most basic recursion (fiber 1 below) is too inefficient. As long as n numbers increase the computing time, it will take a long time. By saving the computation pointer to a dict, this method is used directly for subsequent computation. This method becomes memo. As shown in the following fib2 function, the efficiency is greatly improved.

When n = 10 or less, the running time of fab1 and fab2 is very short, but it is too obvious when n = 40, and it takes 35 seconds to run fab1, fab2 only takes 0.00001 seconds to run.
When n = 40, the output is as follows:

jay@jay-linux:~/workspace/python.git/py2014$ python fibonacci.py 2014-10-16 16:28:35.176396fib1(40)=1023341552014-10-16 16:29:10.479953fib2(40)=1023341552014-10-16 16:29:10.480035

The two functions that calculate the Fibonacci series are as follows: https://github.com/smilejay/python/blob/master/py2014/fibonacci.py

import datetimedef fib1(n):  if n == 0:    return 0  elif n == 1:    return 1  else:    return fib1(n - 1) + fib1(n - 2) known = {0: 0, 1: 1} def fib2(n):  if n in known:    return known[n]   res = fib2(n - 1) + fib2(n - 2)  known[n] = res  return resif __name__ == '__main__':  n = 40  print(datetime.datetime.now())  print('fib1(%d)=%d' % (n, fib1(n)))  print(datetime.datetime.now())  print('fib2(%d)=%d' % (n, fib2(n)))  print(datetime.datetime.now())

Postscript:

It wasn't long before I learned Python, so I was not familiar with its various features. Instead of writing programs in Python, I am writing programs in C, C ++, C #, or Scheme. As for the legendary Pythonic way, I have no experience yet. After all, I have not used Python to write any real programs.
Learning Python and Core Python are both good Python entry books. The former is more suitable for reading by people without programming basics.
Python is one of the best beginner programming languages. Therefore, Scheme can be replaced by MIT's computer programming language.

Articles you may be interested in:
  • C # implement code using the Fibonacci series (recursion, non-recursion)
  • Seven implementation methods for finding the general terms of the Fibonacci series
  • Java Implementation of the fibonacci series learning example sharing (fibonacci series)
  • Example of how to calculate the fibonacci series using cps in C Language
  • Java implements the fibonacci series based on high-precision Integer Data
  • The Go language implements the Fibonacci series method
  • Implement the Fibonacci function for BAT batch processing
  • Java Implementation of the Fibonacci algorithm instance

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.