python-- explain recursive function

Recursive algorithm is an algorithm that calls itself directly or indirectly, of course.

Recursive algorithm to solve the problem of features:

(1) that calls itself recursively in a procedure or function in

(2) When using recursion policy, it must have a clear recursive end condition, called recursive exports.

(3) recursive algorithm solving often are very simple, but lower recursive algorithm solving operational efficiency, it is generally not advocate using a recursive algorithm design program.

(4) In the process of recursive calls for each layer in the system return point, a partial amount of the opened stack to store, easy to cause excessive recursion stack overflow.

2, requires recursive

Recursive algorithm embodied in the "repeat" generally have three requirements:

(1) Each call on the scale have reduced (usually half)

(2) there is a close relationship between the two neighboring repeat, previous to prepare for the time after (usually once entered once before output as a post)

(3) the size of the problem is extremely small must be given direct answers instead of recursive calls, so that each recursive call is conditional (scale level reached directly answer the size of the conditions) will become unconditional recursive calls infinite loop does not end normally.

 

Example: write function, recursive obtain Fibonacci number is the number of 10, and the value is returned to the caller.

1 def foo(depth, a1, a2):
2     if depth == 10:
3         return a1
4     a3 = a1 + a2
5     r = foo(depth + 1, a2, a3)
6     return r
7 
8 ret = foo(1, 0, 1)
9 print(ret)
View Code

 

Guess you like

Origin www.cnblogs.com/june-L/p/11605415.html