This paper describes examples of Hanoi and the Fibonacci series Python recursive algorithm implemented. Share to you for your reference, as follows:
Here we pass two examples, learning to use recursion in python.
- Identify the Fibonacci sequence, the subscript n is a number (index from 0)
Form Fibonacci sequence is this: 0,1,1,2,3,5,8,13 ......
① while loop, 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
Results are as follows:
>>> fib(0)
0
>>> fib(1)
1
>>> fib(2)
1
>>> fib(3)
2
>>> fib(4)
3
>>> fib(5)
5
② recursive (boundary conditions must be recursive), python2 code is as follows:
def fib(n):
if n==0 or n==1:#递归的边界条件
return n
else:
return fib(n-1)+fib(n-2)
Results are as follows:
>>> fib(0)
0
>>> fib(1)
1
>>> fib(2)
1
>>> fib(3)
2
>>> fib(4)
3
>>> fib(5)
5
Recursive algorithm is one of the best performance of computational thinking, we have to f (4) as an example, look at the recursive implementation process:
the same program, although the program is simple to use recursion, but lower than the efficiency of recursive cycle, system resources consumption ratio cycle. Because the recursive call is entered, layer by layer, layer by layer after the end of the return, the recursive efficiency is not high. Why do you have to use recursion? Because there are some problems, we can not find very clear cycle program, but easy to find the obvious recursive program. For example, the famous Tower of Hanoi problem.
- Tower of Hanoi
The figure is a simplified version of the Tower of Hanoi game, only four plates:
Tower of Hanoi game as
python2 code is as follows:
def hanoi(a,b,c,n):
if n==1:#递归结束条件
print a,'->',c
else:
hanoi(a,c,b,n-1)
print a,'->',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
Finally, I recommend a good reputation python gathering [ click to enter ], there are a lot of old-timers learning skills, learning experience, interview skills, workplace experience and other share, the more we carefully prepared the zero-based introductory information on actual project data method, every day, programmers explain the timing Python technology, to share some of the learning and the need to pay attention to small details