Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is recursive and recursive traversal of directories in Python

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail about recursion and recursive traversal of directories in Python. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Recursion

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

Usage scenario: if you find that what you are going to do is what you are doing now, use recursion

Recursion is like a loop; when writing or reading recursion, we first focus on the termination condition of recursion.

Recursive summation

Before we touch on recursion, let's start with this question: if we want to sum a list of numbers (or any other sequence), what else can we do but use the built-in sum function?

While cycle

L = [1 mysum 2 3 Magne4] mysum = 0 # variable saved and mysum L: # add the value of the first position of the list to the sum L = L [1:] # remove the first element of the list every time

For cycle

L = [1, mysum 2, 3, 4, 5] mysum = 0for 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 call to a function and pass a parameter that handles the nonlinear loop recursively without the new list of the first element in the current list

Recursive return can handle some non-linear loops, while ordinary loops cannot; for example, a list summing it:

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

Since this list is not a linear iteration and contains complex element nesting, ordinary loop statements will be very difficult to control.

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

Think about it: if you have 10000 yuan, spend half of it every day, and give up the dime directly, how many days will it take?

Recursive solution:

Def cost (money,day=0): if money > 0: money = money / / 2 # spend half at a time day + = 1 # spent days + 1 cost (money,day) # enable money recursive else: print ('total% d days'% day) return # A recursive consideration of termination condition is required

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

This is because every time a recursive function is executed, a new copy of the function is generated in memory, and the memory consumption of the recursion is greater than that of the ordinary loop.

> def func (): Return func () Traceback (most recent call last): File ", line 1, in File", line 2, in func [Previous line repeated 995 more times] RecursionError: maximum recursion depth exceeded# here we go online and report an error after 995 recursions.

We can also manually interfere with the upper limit of recursion, but this is risky and should be considered in the light of the computer's own memory.

> import sys > sys.setrecursionlimit (num) # num implements the Tree command to control the maximum number of recursive changes

The core idea is that the depth and breadth of the directory structure is complex, and it is very difficult to make a decision through a simple loop.

Recursion is just suitable for this kind of nonlinear loop problem, of course, it also has some disadvantages. When the directory structure becomes more and more complex, then the execution efficiency of the program will become worse and worse.

Import osdef getdir (path, level=0): if path = ='': path = os.getcwd () # get the current working directory level + = 4 num = level / / 4 abs_path = os.path.abspath (path) for name in os.listdir (path): # returns a list format_str =''if os.path.isfile (os.path.join (abs_path Name): for var in range (num): # range function is used to control the number of cycles 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): # range function to control the number of loops format_str + ='_'* 4 + '▕' # output style construction format_str + = name mystr = format_str.replace ('_','' Level-4) # replace level-4 _ print (mystr) # output format string name = os.path.join (abs_path,name) if os.path.isdir (name): # absolute path to determine whether it is a folder getdir (name) Level) path = input ('Please enter the directory you want to traverse:') getdir (path) about recursion in Python and how recursive traversal directories are shared here I hope the above content can be of some help to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report