Recursive thinking

Demand: Calcd 1 * 2 * 3 * .... * 1000

General codes:

def func(arg):
    res = 1
    for i in range(1, arg):
         res *= i
    return res

 Recursive method:

def fun(arg):
    if arg == 1:
        return 1
    return arg*(fun(arg-1))

 

  •  This function is found, the final return of function is an expression of the function itself, if less than 5 factorial calculation, his work as follows:
  1. fun (5) calls the function fun () function, then arg = 5,5> 1, it will return 5 * fun (4)
  2. fun (4) calls fun () function, then arg = 4,4> 1, it will return 4 * fun (3)
  3. fun (3) calls fun () function, then arg = 3,3> 1, it will return 3 * fun (2)
  4. fun (2) calls fun () function, then arg = 2,2> 1, it will return 2 * fun (1)
  5. fun (1) calls fun () function, then arg = 1,1 = 1, it will return 1
  6. When fun (1) the value returned to the fun (2), this time fun (2) = fun (1) * 2 = 2, continue up to the return to fun (3)
  7. When fun (2) returns a value to fun (3), this time fun (3) = fun (2) * 3 = 6, returns to continue up fun (4)
  8. When fun (3) returns a value to fun (4), this time fun (4) = fun (3) * 4 = 24, returns to continue up fun (5)
  9. When fun (4) returns a value to fun (5), this time fun (5) = fun (4) * 5 = 120, yielding a result of
  • Creating Recursive conditions
  1. A baseline conditions: Condition recursive termination, the need to judge the beginning recursive process.
  2. A series of rules: to make each call to converge on a recursive function until the baseline condition

Recursion can improve the readability of the code, but lower operating efficiency. In the process of recursive call system return point for each layer, the amount of local storage stack to open up the like. Recursive too many times likely to cause a stack overflow.

Guess you like

Origin www.cnblogs.com/dyuan8888/p/11930080.html