我有一个数据库,模拟与n级嵌套的文件夹关系.对于任何给定的文件夹,我想生成所有子文件夹的列表.
假设我有一个名为getChildFolders()的函数,调用这种递归循环的最有效方法是什么?
以下代码适用于4个嵌套级别,但我希望在指定递归深度时更灵活,或者在没有更多子级要遵循的情况下智能地停止循环.
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)
解决方法:
递归函数是一种很好的方法:
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
标签:python,loops,recursion,nested