Recursive functions are simply called self-invocation of functions. Using recursive functions can often make code simple and elegant. Complex problems can be broken down into simple sub-problems. Recursion has unparalleled charm, and from famous computer sayings you can see the wonders of recursion:
is human,to recurse Divine. The iteration is human and the recursion is God. –l Peter Deutsch
In fact, the above sentence is a bit exaggerated, recursion is not perfect, it also has a fatal weakness, that is inefficient execution, and easy to lead to stack overflow (more than 1000 times).
Let's take a look at the recursion from a wonderful diagram.
We use a simple example to compare the difference between recursion and iteration: to find the factorial of n
Here's how to use iterations:
def Jiecheng (n): result=1 for inch range (N): result*= (i+1) print('factorial of%d'%d ' %(N,result))
Jiecheng (5) #5的阶乘为120
Here's how to use recursion:
def Jiecheng (n): if n==1: return 1 else: return n * (Jiecheng (n-1))
You can see that using recursion can make your code more concise and elegant, and more mathematically beautiful.
The following is a discussion of recursion through the Fibonacci sequence:
1, through the loop to achieve:
A=0b=1 while B <: print (b)= B, a+b
2, the ordinary recursive implementation of the Fibonacci sequence:
1 ls=[]2 for in range:3 ifor i ==1:4 ls.append (1)5 else: 6 Ls.append (ls[i-2]+ls[i-1])7print(ls) #[1, 1, 2, 3, 5, 8, 13, 21 , the "
3, through the tail recursive way to achieve:
def Fbnq (n,a,b): if n==0: return (b) Else: return FBNQ (n-1,b,a+b)print for in range (5)])
These three methods are actually the highest iterative efficiency, and then
Python recursive functions