# recursive functions # inside a function, other functions can be called. If a function calls itself internally, this function is the recursive function # computes n!def fact (n): if n == 1: return 1 return n * fact ( n - 1) Print (fact (1)) Print (Fact (5)) The advantage of # recursive function is that the definition is simple, the logic is clear # theoretically, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion # Using recursive functions to prevent stack overflow # in a computer, a function call is implemented through a stack (stack) of such a data structure # whenever a function call is entered, the stack will add a stack frame, and whenever the function returns, the stack will be reduced by a stack frame # Because the size of the stack is not infinite, too many recursive calls can cause stack Overflow # fact (# ) The method of resolving recursive call stack overflow is optimized by tail recursion, in fact, the effect of tail recursion and loop is the same # so, It is also possible to think of loops as a special kind of tail recursive function. # tail recursion means that when a function returns, it calls itself, and the return statement cannot contain an expression # so that the compiler or interpreter can optimize the tail recursion, so that the recursion itself no matter how many times it is called, All occupy only one stack frame, there is no stack overflow situation # above the fact (n) function because Return n * fact (n - 1) introduced a multiplication expression, so it is not a tail recursive # To change to tail recursion, need a little more code, the main thing is to pass the product of each step into the recursive function def fact (n): return fact_iter (N, 1) Def fact_iter (num, product): if num == 1: return product return fact_iter (num - 1, NUM * PRODUCT) # can see that Return fact_iter (num - 1, num *  PRODUCT) returns only the recursive function itself # num - 1 and num * product are evaluated before the function call, without affecting the function call print (fact (5)) # tail recursive invocation, if optimized, the stack does not grow, so no matter how many calls will not cause a stack overflow # the advantage of using a recursive function is that logic is simple and clear, the disadvantage is that too deep calls can cause stack overflow # The language of tail recursion optimization can prevent stack overflow by tail recursion # tail recursion in fact, the loop is equivalent, the programming language without the loop statement can only be implemented by the tail recursive # python standard interpreter is not optimized for tail recursion, any recursive function has stack overflow problem
Python---recursive functions