+ 2
Recursion doubt
Can anyone explain about recursion ??
1 Answer
+ 3
Recursion is when a function calls itself over and over again as it works it's way through a problem. Then, when it reaches the end of the problem, it returns. Recursion may be used for exploring data such as hierarchical data or in sorting algorithms.
The rules for recursive function is that must have some test that tells it when the work is done. That's called a BASE CASE. When a base case is reached, it returns back out. You could think of it as being a bit similar to a for loop.
Here is an example of a function that digs through a directory structure. If it finds a file, print. If it finds a folder, it calls itself again to explore that folder. It digs until it can't dig any more and then returns up a level to continue.
from pathlib import Path
def list_files(directory):
# Convert string to Path object if needed
dir_path = Path(directory)
# Iterate through directory contents
for item in dir_path.iterdir():
if item.is_file():
print(item)
else:
# if item.is_directory():
list_files(item) # Recurse into subdirectories
# Example usage:
list_files(".")