Python11 recursive function

recursive function

  • Understanding: a function calls itself itself, this function is a recursive function internally.
  • Advantages: the advantage of a simple recursive function is defined, clear logic. In theory, all recursive functions can be written in a circular fashion, but not as good as recursive loop logic is clear.
  • Recursive function examples:
    • Factorial :
      • Code:
        `` `
        # factorial - recursive function implemented: factorial Example 3:. 1. 1 * 2 * 3 *
        DEF factorial (X):
        IF Not the isinstance (X, (int)) or X <0: parity parameter type # must be a positive integer or 0
        the raise TypeError ( "parameter x type must be a positive integer")
        elif x == 0:
        return. 1 # 0 factorial is. 1
        the else:
        return x * factorial (x-. 1)
        # exploded return x * factorial ( . 1-X)
        # 3 = X, the result is 3 * factorial (3-1) (i.e. x = 2)
        when 2 # x =, the result is 2 * factorial (2-1) (i.e.,. 1 = X)
        # X = 1, the result is 1 * factorial (1-1) (i.e.,. 3 = X)
        # X = 0, the result is 1
        # 2 * final results 1 * *. 3 1
        Print (factorial (. 3))

        ```
      • operation result:
        maSqdP.png
      • Stack overflow: in the computer, the function call is achieved through the stack (Stack) This data structure, each time a function call into the stack a stack frame is increased by one, each time the function returns, the stack will decrease layer stack frame. As the stack size is not unlimited, so the number of recursive calls too, can cause a stack overflow
        • Stack overflow example:
          mapsfS.png
        • Solution: 尾递归优化tail recursion means that, when the function returns, calls itself itself, and, return statement can not contain expressions. In this way, the compiler or interpreter you can do to optimize tail recursion, the recursive call to itself, no matter how many times, only occupy a stack frame, stack overflow situation does not occur.
        • Example optimized tail recursion: https://www.liaoxuefeng.com/wiki/1016959663602400/1017268131039072

Guess you like

Origin www.cnblogs.com/thloveyl/p/11391735.html