I would like to discuss recursion in Python as a topic. When I was learning, I tried to use "Python recursion" as a keyword and searched in Google and Baidu. I found that most of the results were about recursive applications of a specific example, for me, the entry point is a bit high. What I need to do now is to start with the basic concepts.
We thought about recursion because of the famous "Lexicographic Order", but we started with the most basic concept of recursion. I hope that after I have discussed this, I have a basic understanding of recursion.
The concept of recursion is very simple. If a function contains calls to itself, this function is recursive. The definition of the logging interface is that if a new call can start before the end of an earlier call in the same process, the process is recursion. Both definitions come from page 304th of Python core programming version 2.
This book uses a classic example to describe recursive applications:
The factorial function is defined as follows:
N! = Factorial (n) = 1*2*3 *... * n
In this way, we can look at the factorial function:
Factorial (n) = n!
= N * (N-1 )!
= N * (N-1) * (N-2 )!
= N * (N-1) * (N-2) *... * 3*2*1
= N * factorial (n-1)
So we have the recursive version of the factorial function:
Def factorial (n ):
If n = 0 or n = 1: return 1
Else: return (n * factorial (n-1 ))
Print factorial (6)
You can easily get it, 6! The result is 720.
The above is the content of this book about recursion, but is there more than just a little knowledge about Python recursion?
Let's take a look at this problem:
This function is still factorial (N). Let's try N = 999 and N = 1000. The question is, when N = 999, the correct answer can be output, but when N = 1000, the following error occurs:
RuntimeError: maximum recursion depth exceeded
Therefore, remember that the default Python has a limit on the available recursive depth to avoid exhausting the memory in the computer. On my computer, this is 1000.
Next let's take a look at the problems I encountered in my first recursive program:
To try it out, I plan to write a traditional problem of simple function compute, 1 + 2 + 3 +... + 100. Of course, recursion is required:
My script is like this and the result is incorrect.
>>> Def add (n ):
... If n> 0: return n + add (n-1)
...
>>> Add (100)
Traceback (most recent call last ):
File "<stdin>", line 1, in?
File "<stdin>", line 2, in add
File "<stdin>", line 2, in add
...
File "<stdin>", line 2, in add
TypeError: unsupported operand type (s) for +: 'int' and 'nonetype'
After asking online, I learned that this script should be written as follows:
>>> Def add (n ):
... If n <= 0: return 0
... If n> 0: return n + add (n-1)
...
>>> Add (100)
5050
I wanted to be lazy. When n is less than or equal to zero, nothing is returned. But what Pyhton does is different from what I think. If a Python function is designed to return nothing, it returns None.
Here we will insert some network explanations about recursion, because I found these content on the Internet:
(1) recursion is to call itself in a process or function;
(2) When using a recursive policy, there must be a clear recursive termination condition called the recursive exit.
Recursive Algorithms are generally used to solve three types of problems:
(1) data is defined recursively. (For example, the Fibonacci function)
(2) The problem solution is implemented by recursive algorithms. (Backtracking)
(3) The data structure is defined by recursion. (For example, tree traversal and Graph Search)
Disadvantages of recursion: the efficiency of solving recursive algorithms is low. During the recursive call process, the system opens a stack for storing the return point and local volume of each layer. Too many recursion times may cause stack overflow.
[Recommendation] net article "proficient in recursive Program Design":
Http://www.ibm.com/developerworks/cn/linux/l-recurs.html
The basic steps of recursive Programs are from the above article
Every recursive program follows the same basic steps:
1. initialize the algorithm. Recursive programs usually need a seed value used at the beginning ). To complete this task, you can pass parameters to the function or provide an entry function. This function is non-recursive, but can set a seed value for Recursive calculation.
2. Check whether the current value to be processed matches the baseline condition (base case ). If yes, it is processed and returned.
3. Use smaller or simpler subquestions (or multiple subquestions) to redefine the answer.
4. Run algorithms on subproblems.
5. The expression that combines the result into the answer.
6. Return results.
Baseline condition (base case ). The baseline condition is the bottom-layer position of the recursive program. If you do not need to perform any operations at this position, you can directly return a result. All recursive Programs must have at least one baseline condition and must ensure that they will eventually reach a baseline condition; otherwise, the program will run forever until the program lacks memory or stack space.
To write a recursive program, you need to do the following:
1. A baseline condition. Process the baseline condition at the beginning of the recursive function.
2. A series of rules enable every call to a recursive function to continue until the baseline condition is met.
Well, now it seems that the basic concepts are almost the same. Before returning to the "lexicographically ordered" issue, let's take a look at the full Sorting Problem. The requirement for a question is very simple. Input n numbers to automatically print out the full arrangement (Permutation ). For example, if the input values are 1, 2, 3, the entire array is 123,132,213,231,312,321.
[Reference]
In the Pyhon core programming Second Edition 209th page eighth chapter exercise continued, Question 8-6 in the function findPrimeFactors using recursion, can refer to: http://www.cnblogs.com/balian/archive/2012/01/11/2318679.html
[Recommendation] blog: CoderZh technical blog
Http://www.cnblogs.com/coderzh/articles/1202040.html