Below from a beginner's point of view as close as possible, to give you a detailed understanding of recursion in Python.
I. recursion Recursive Call: A function that calls itself, called a recursive call Recursive function: A function that can call itself is called a recursive function. Recursion can do everything that can be done in a cycle.
Method:
1. Write out the critical conditions.
2. Find the relationship between this time and last time.
3. Assuming that the current function can be used, call the result of the last calculation to get the result of this time.
Let's take a brief look at the difference between recursive and non-recursive in two sections of code.
Enter a number greater than or equal to 1, and find the sum of 1 to 1! uuuuuuuuuuuu
1 # Common Function Method 2 3 def hanshu(n): 4 sum = 0 5 6 for x in range(1, n+1): 7 sum += x 8 return sum Let's look at the recursive approach: 1 recursion 2 3 def digui(n): 4 if n == 1: 5 return 1 # If n equals 1 to prove that it has recurred to the end, return 1, this is the critical condition mentioned above. 6 else: 7 return n + Digui (n-1)# When the critical condition is not reached, add n to n-1 recursion with n, and add n to n every time, but then use the current recursive function, will call the calculation of n-1 again until the end of the recursion, that is, all the numbers from n to 1 will be recursively completed.
In practice, recursion consumes a lot of memory, but there are some things he can easily do and understand. Next, I will introduce the use of recursion through a case study.
2. Recursive traversal of directories The following is explained by explaining the code. If you don't know where to say it clearly, you are welcome to comment below.
1 import os # Since we traverse the directory, to find that directory and operate on it, the os module contains general operating system functions 2 3 path = "" # This is the path to the directory we're going to traverse. We need to write it in by ourselves. 4 5 # Since it is a recursive function, there must be a function, and the function will be called again inside the function. 6 def getAllDir(path, sp = ''): # Pass in paths and SPS in parameters, which I'll say last, and you'll see. 7 # Get all the files in the current directory 8 filesList = os.listdir(path) # os.listdir() is a method under the os module, equivalent to ls in Linux, to view all files 9 10 sp += " " # Let's put this in first. 11 # Processing each file 12 for fileName in filesList: # Go through all the files in the directory you just found 13 # Determine whether it is a directory (absolute path)? 14 fileAbsPath = os.path.join(path,fileName) # join is the meaning of splicing two paths under os module. The second parameter can not have slash. Because we have to decide whether the file is a regular file or a directory, we have to sort out its absolute path first. 15 if os.path.isdir(fileAbsPath): # isdir determines whether it is a directory or not, and returns True 16 print(sp + "Catalog:", fileName) # Print the current file. It's a directory. 17 getAllDir(fileAbsPath,sp = " ") # This is where recursion begins, because we want to find things in the entire directory, so when this file is still a directory, we need to continue looking down. 18 else: 19 print(sp + "Ordinary documents:", fileName) # If it's just an ordinary document, there's no other document in it, so you can print it directly. 20 21 22 getAllDir(path) # Here is the call function to start the traversal 23 24 # Finally, let me talk about the sp I started writing, which means space. Some people may understand it now. That is actually to make it easy for us to observe, because each print is written on the top line, we can not distinguish his directory structure, so we adjust it by blank space. Write an expression to increase the number of blanks in the function, which can correlate the number of calls with the number of blanks. The deeper the recursion, the lower the level of the directory, the more blanks there are.
Third, stack simulation recursive traversal directory (depth traversal)
1 # The whole idea hasn't changed. What hasn't been written here may be repetitive. Just look at the notes above. 2 # The stack is a container, but it has only one port. The stack is from this port, and the stack is very thin. When it enters, it can't reverse its position. Therefore, every element in the stack can come out at the outermost time, otherwise it can only come out when the front one is finished. 3 import os 4 5 def getAllDirDFS(path): 6 stack = [] # Here we use stack to simulate. Let's first create a list as stack. 7 stack.append(path) # First, press the path into the stack 8 9 # Processing stack, end the loop when the stack is empty (empty stack means that there are no ordinary files and directories in the stack, because we need to take that out for each operation) 10 while len(stack) != 0: 11 # Remove data from the stack 12 dirPath = stack.pop() # The pop function deletes the last element and also has a return value, which is the removed element. Let's accept it and wait. 13 # All files in the directory 14 filesList = os.listdir(dirPath) # This is the same as above. 15 16 # Processing each file, printing out if it is a normal file, and stacking the directory address if it is a directory 17 for fileName in filesList: 18 # print(dirPath) 19 fileAbsPath = os.path.join(dirPath,fileName) 20 # print(fileAbsPath) 21 if os.path.isdir(fileAbsPath): 22 # If it's a directory, it's a stack. 23 print("Catalog:" + fileName) 24 stack.append(fileAbsPath) # When the directory is in the stack, it is at the outermost, the next cycle to take out the elements of the stack is still this ah, since it is, there is still something inside him, and wait until he finds out before continuing to find those files parallel to him. That is to say, grabbing a rope and searching down hard, finding the head and returning without it. This is depth first traversal. 25 else: 26 # Print ordinary documents 27 print("Common:" + fileName) 28 29 getAllDirDFS(path)
4. Queue simulation recursive traversal directory (breadth traversal)
1 # This time, remember, first of all, the queue is a model with two openings at each end, one in and one out, of course, two-way queues, loops and so on. Let's simply use the most basic queue. 2 3 import collections # The queue is in python's bag, so let's call it directly. Don't think it's difficult. It's just queue. The actual idea is the same. Entry append, because this is on the right side, that is, behind the queue, and the other side is popleft, left out. Is it very popular, just changed the exit? 4 def getAllDirBFS(path): 5 queue = collections.deque() # Create a queue, just remember that the following usage is the difference I said above. 6 queue.append(path) 7 8 while len(queue) != 0: 9 dirPath = queue.popleft() # It's just different here, because queue simulation is the other end of the queue. 10 filesList = os.listdir(dirPath) 11 for fileName in filesList: 12 fileAbsPath = os.path.join(dirPath,fileName) 13 if os.path.isdir(fileAbsPath): 14 print('Catalog:' + fileName) 15 queue.append(fileAbsPath) 16 else: 17 print('Document:' + fileName) 18 19 getAllDirBFS(path) 20 21 # Let's think about where the stack goes in and where it goes out, that is, the elements just in, and the next cycle comes out, that is, one way to the end, deep traversal; then what does it mean to go in and out at one end, that is, even if it is judged to be a directory, but I will not execute you now, I will look up all of your previous ones, and find out the directory. All of them are added to the back, and then traverse all of you. That is to find the content of one layer and the next one. It is called breadth first traversal.
If Python programming, web crawler, machine learning, data mining, network development, artificial intelligence, interview experience exchange. Interested in my blog. (Origin: https://blog.csdn.net/Stephen_shijun/article/details/83182807 )