This article mainly introduces Python based on recursive algorithm implementation of Hanoi and Fibonacci series, combined with the example form analysis of Hanoi and Fibonacci sequence of recursive implementation skills, the need for friends can refer to the next
In this paper, the Hanoi and Fibonacci sequence of Python based on recursive algorithm are described. Share to everyone for your reference, as follows:
Here we learn the use of recursion in Python through 2 examples.
1. Find the number of subscript n in the Fibonacci sequence (the subscript is counted from 0)
The form of the Fibonacci sequence is this: 0,1,1,2,3,5,8,13 ...
① uses the while loop, and the Python2 code is as follows:
def fib (n): a,b=0,1 count=0 while count<n: a,b=b,a+b count=count+1 Print a
The results of the operation are as follows:
>>> fib (0)
0
>>> fib (1)
1
>>> fib (2)
1
>>> fib (3)
2
>>> fib (4)
3
>>> fib (5)
5
② using recursion (recursion must have boundary conditions), the Python2 code is as follows:
def fib (n): if n==0 or n==1: #递归的边界条件 return n else: return fib (n-1) +fib (n-2)
The results of the operation are as follows:
>>> fib (0)
0
>>> fib (1)
1
>>> fib (2)
1
>>> fib (3)
2
>>> fib (4)
3
>>> fib (5)
5
Recursion is one of the most expressive algorithms of computational thinking, and we take the example of F (4) and look at the recursive execution process:
The same program, using recursion although the program is concise, but the efficiency of recursion is lower than the cycle, the system's resource consumption is larger than the cycle. Because recursion is a layer to the inside of the call, and after the end of a layer of return, so the recursive execution efficiency is not high. So why use recursion? Because there are some problems, we can not find a very obvious loop scheme, but it is easy to find the obvious recursive scheme. For example, the famous question of the Nottingham Tower.
2. Hanoi
is a simplified version of the Hanoi game, with only 4 plates:
Hanoi game rules are as follows:
The Python2 code is as follows:
def Hanoi (A,b,c,n): if n==1: #递归结束条件 print A, '-a ', C else: Hanoi (a,c,b,n-1) print A, '-I ', C Hanoi (b,a,c,n-1)
Operation Result:
>>> Hanoi (' A ', ' B ', ' C ', 1)
A-C
>>> Hanoi (' A ', ' B ', ' C ', 2)
A-B
A-C
B-C
>>> Hanoi (' A ', ' B ', ' C ', 3)
A-C
A-B
C-B
A-C
B-A
B-C
A-C