SoFunction
Updated on 2024-11-10

Recursion in Python and recursive traversal of directories in detail

recursive (calculation)

The concept of recursion: a function contains a call to itself, then it is recursive

Scenarios for use: If you realize that what you're about to do is what you're doing now, then use recursion

Recursion is similar to a loop; when writing or reading about recursion, the first thing we focus on is the termination condition of the recursion

Recursive Summation

Before touching on recursion, let's do this: what is the best way to, say, sum a list of numbers (or any other sequence), other than the built-in sum function that we can use?

while loop

L = [1,2,3,4,5]
mysum = 0 # Variables that hold sums
while L: #Let the list be the most recurring condition
	mysum += L[0] # Add the value in the first position of the list to the sum each time
	L = L[1:] # Remove the first element of the list

for loop

L = [1,2,3,4,5]
mysum = 0
for var in L:
	mysum += var

Recursive Summation

def mysum(L):
    if not L:
        print ('L is empty')
        return 0
    else:
      	return L[0]+mysum(L[1:])
# In the return value, we return a function call and pass the parameter as a new list with the first element of the current list removed

Recursive handling of nonlinear loops

Recursion can also handle non-linear loops that ordinary loops can't; for example, a list like this sums over it:

L = [1,[2,[3,4],5],6,[7,8]]

Since this list is not a linear iteration, and contains complex nesting of elements, it will be very difficult to control the processing of ordinary looping statements

L = [1,[2,[3,4],5],6,[7,8]]
sum = 0
def mysum(L):
    global sum
    for var in L:
    	if not isinstance(var,list):   
            # If one of the elements is not of list type, it is a definite value
            sum += var
        else:
         	mysum(var)
    return

spend money recursively

Think: If you have $10,000 and you spend half of it every day, with the gross money just rounded up, how many days can you spend that money?

Recursive solution:

def cost(money,day=0):
    if money > 0:
        money = money // 2 # Spend half at a time
        day += 1 # of days spent +1
        cost(money,day) # Turn on the spend recursion
    else:
        print('It can take a total of %d days' % day)
        return # There must be a termination condition

Recursive Considerations

In Python, the maximum number of recursions is almost 998, and a recursion without a termination condition will raise an error (similar to a dead loop)

This is because each function execution of recursion generates a new copy of the function in memory, and the memory consumption of recursion is greater than that of a normal loop

>>> def func():
...     return func()
...
>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func
  File "<stdin>", line 2, in func
  File "<stdin>", line 2, in func
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
# Here we reach the top line after 995 recursions, thus reporting the error

We can also manually intervene in the upper limit of the recursion, but this is risky and has to be considered in the context of the computer's own memory

>>> import sys
>>> (num)
# num is the maximum number of recursion caps for control modifications

Implementing the Tree command

The core idea is that the depth and breadth of the directory structure is intricate, and making a determination by simply looping through it is a very difficult thing to do.

Recursion is suitable for such non-linear loops, but of course there are some drawbacks, as the directory structure becomes more and more complex, the program execution efficiency will become worse and worse.

import os

def getdir(path, level=0):
    if path == '':
      	path = ()  # Get the current working directory
    level += 4
    num = level // 4
    abs_path = (path)
    for name in (path):  # The return is a list
        format_str = ''
        if ((abs_path, name)):
            for var in range(num):  # The range function is used to control the number of loops
              	format_str += '_' * 4 + '▕'
            format_str = format_str[0:-1]
            format_str += name
            mystr = format_str.replace('_', ' ', level-4)  # Replace level-4 _
    else:
        for var in range(num): # The range function is used to control the number of loops
            format_str += '_' * 4 + '▕' # Output style constructs
        format_str += name
        mystr = format_str.replace('_',' ',level-4) # Replace level-4 _
    print(mystr) # Output format string
    name = (abs_path,name)
    if (name): # Absolute path, determine if it is a folder
	    getdir(name,level)
path = input('Please enter the directory you want to traverse:')
getdir(path)

summarize

This article on Python recursion and recursive traversal of the directory of the article is introduced to this, more related to Python recursive traversal of the directory of content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!