I have a database that models a foldering relationship to n levels of nesting. For any given folder, I want to generate a list of all child folders.
Assuming I have a function called getChildFolders(), what is the most efficient way to call this kind of recursive loop?
The following code works for 4 levels of nesting, but I'd like more flexibility in either specifying the depth of recursion, or in intelligently stopping the loop when there are no more children to follow.
folder_ids = []
folder_ids.append(folder.id)
for entry in child_folders:
folder_ids.append(entry.id)
child_folders_1 = getChildFolders(entry.id)
for entry_1 in child_folders_1:
folder_ids.append(entry_1.id)
child_folders_2 = getChildFolders(entry_1.id)
for entry_2 in child_folders_2:
folder_ids.append(entry_2.id)
child_folders_3 = getChildFolders(entry_2.id)
for entry_3 in child_folders_3:
folder_ids.append(entry_3.id)
解决方案
A recursive function is a nice way to do this:
def collect_folders(start, depth=-1)
""" negative depths means unlimited recursion """
folder_ids = []
# recursive function that collects all the ids in `acc`
def recurse(current, depth):
folder_ids.append(current.id)
if depth != 0:
for folder in getChildFolders(current.id):
# recursive call for each subfolder
recurse(folder, depth-1)
recurse(start, depth) # starts the recursion
return folder_ids