(Xvii) python 3 recursive function

recursive function

That calls itself recursively call itself can function itself, but the conditions are similar to the use of the same cycle, there must be recursive termination condition

  • Pros: When using recursion, often makes the code more concise
  • Disadvantages: it takes up more memory recursive, recursion when the number of comparisons for a long time, the performance will be reduced, and therefore is not recommended more use of recursion
Recursive nature:
# 1. There must be a definite end condition
# 2. Every time when deeper into the recursive, recursive problem size should be reduced compared to last
# 3 recursive efficiency is not high, too many levels of recursion can cause a stack overflow (in the computer, the function call is achieved through the stack (stack) this data structure, whenever entering a function call, the stack will add a layer stack frame, whenever the function returns, the stack will cut a layer stack frame. Since the size of the stack is not infinite, so the number of recursive calls too much will result in a stack overflow)

Simple recursive function

Depending ef (n):
    if n == 1:
        return n
    elif n > 1:
        return n * func(n - 1)
    else:
        return 'pass the parameter is greater than zero'

print(func(5))

'''result:
120
Equivalent to 1 * 2 * 3 * 4 * 5 = 120
'''

  

 

Guess you like

Origin www.cnblogs.com/a-ant/p/11013153.html