python recursive function

Python is inside a function and can call other functions. If a function calls itself internally, this function is a recursive function

Write a recursive function def   func (n) for factorial:

    n == :
        n * func(n-)
(func())

The use of recursive functions requires attention to prevent stack overflow. In computers, function calls are implemented through the data structure of the stack. Whenever a function call is entered, a stack frame will be added to the stack. Whenever the function returns, the stack A stack frame will be reduced by one layer. Since the size of the stack is not infinite, too many recursive calls will lead to stack overflow. The case is as follows

blob.png


The way to solve the recursive call stack overflow is through tail recursion optimization. In fact, the effect of tail recursion and loop is the same. Therefore, it is also possible to regard loop as a special tail recursion function.


Tail recursion means that when the function returns, it calls itself, and the return statement cannot contain expressions. In this way, the compiler or interpreter can optimize the tail recursion, so that no matter how many times the recursion itself is called, it only occupies one stack frame, and there will be no stack overflow.

The above func(n) function is not tail recursive because return n*func(n-1) introduces a multiplication expression. To change to tail recursion requires a little more code, mainly to pass the opportunity of each step into the recursive function:

(n):
    fact_iter(n)
(numproduct):
    num == :
        product
    fact_iter(num-num*product)
(fact())

When tail-recursive calls are made, the stack will not grow if optimized, so no matter how many calls are made, the stack will not overflow

Unfortunately, most programming languages, including python, do not optimize tail recursion, so changing the above fact() function to tail recursion will also lead to stack overflow

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324739635&siteId=291194637