First, recursive function
Concept: recursive algorithm is a direct or indirect process of invoking its own algorithm. In computer programming, recursive algorithm is very effective to solve a large class of problems.
Characteristics:
① recursion is the invocation of itself in a procedure or function.
② when using a recursive strategy, there must be a definite recursive condition called a recursive exit.
③ recursive algorithm is usually very concise, but the recursive algorithm is less efficient in solving problems. Therefore, we generally do not advocate the use of recursive algorithm design program.
④ in the process of recursive invocation, each layer of the system's return points, local variables, etc. open up a stack to store. Too many recursive functions tend to cause stack overflow and so on.
Therefore, the recursive algorithm is generally not advocated for the design of the program.
Requirements:
The recursive algorithm embodies the "repetition" generally has three conditions:
The ① is scaled down (usually halved) every time the call is scaled.
② There is a close connection between two repetitions, the previous one to be prepared for the next (usually the previous output as the last input).
③ must use direct contact solution instead of recursive invocation when the scale of the problem is minimal, so that each recursive invocation is conditional (with the size not reaching the direct solution),
An unconditional recursive call will become a dead loop and not end normally.
1 """rendering in a non-recursive manner"""2sum =03 forObjinchRange (1,101):4sum+=obj5 Printsum6 7 """"1+2+3+...+100"""8 deffoo (n):9 ifN>0:returnN+foo (n-1)Ten ifN<=0:return0 One PrintFoo (100) A - """factorial""" - defFAC (n): the ifN==0orN==1: - return1 - Else: - returnN*FAC (n-1) + PrintFAC (10)
Recursive algorithms are generally used to solve three types of problems:
(1) The definition of the data is defined by recursion. (e.g. Fibonacci function)
(2) The problem solution is implemented by recursive algorithm. Back
(3) The structural form of the data is defined by recursion. (such as the traversal of trees, the search of graphs, the dichotomy of finding, etc.)
Recursive implementation of Python