Recursive functions
Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.
For example, let's calculate factorial n! = 1 * 2 * 3 * ... * n, denoted by the function fact (n), you can see:
Fact (n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact (n-1) * n
So, fact (n) can be represented as N * fact (n-1), and only n=1 requires special handling.
So, fact (n) is written in a recursive way:
def fact (n): if N==1:return 1return n * Fact (N-1)
Above is a recursive function. You can try:
>>> Fact (1)
1
>>> Fact (5)
120
>>> Fact (100)
9332621544394415268169923885626670049071596826438162146859296389521759999322991560894146397615651828625369792082722375825 1185210916864000000000000000000000000L
If we calculate the fact (5), we can see the calculation process according to the function definition as follows:
===> Fact (5)
===> 5 * FACT (4)
===> 5 * (4 * FACT (3))
===> 5 * (4 * (3 * FACT (2)))
===> 5 * (4 * (3 * (2 * FACT (1)))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120
The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.
The use of recursive functions requires careful prevention of stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow. You can try to calculate fact (10000).
def Digui (n): sum = 0if n<=0:return 1else:return N*digui (n-1) Print (Digui (5))
Python Recursive functions