Python can call other functions inside the function, and if a function calls itself internally, the function is a recursive function
Write a factorial recursive function def func(n):
n = =: N * func (N) (func ())
The use of recursive functions need to pay attention to prevent stack overflow, in the computer, function calls through the stack (stack) This data structure implemented, whenever a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack frame, because the size of the stack is not infinite, so the number of recursive calls too many, Will cause the stack to overflow, the case is as follows
The method of solving recursive call stack overflow is optimized by tail recursion, in fact, the effect of tail recursion and loop is the same, so it is possible to think of the loop as a special tail recursive function.
tail recursion means that when a function returns, it calls itself, and thereturn statement cannot contain an expression. In this way, the compiler or interpreter can optimize the tail recursion, so that the recursive itself, no matter how many times it is called, consumes only one stack frame, and no stack overflow occurs.
The func (n) function above introduces a multiplication expression due to return N*func (n-1), so it is not a tail-recursive. To change to a tail recursion requires a bit more code, mainly to pass the flight of each step into the recursive function:
(n): Fact_iter (n) (numproduct): num = =: Product Fact_iter (num-num*product) (Fact ())
Tail recursive invocation, if optimized, the stack does not grow, so no matter how many calls will not cause a stack overflow
Unfortunately, most programming languages, including Python, do not optimize for tail recursion, so changing the above fact () function to tail recursion can also lead to stack overflow
Python recursive functions