【发布时间】:2022-01-26 03:17:19
【问题描述】:
我一直在尝试为下面的代码示例编写一个递归函数,但我面临的问题是我的循环在下次运行时会翻倍。
def get_choices():
choices = []
nodes = Node.query.filter_by(parent_id=None).all()
for node in nodes:
choices.append((node.id, f"{node.value}"))
if node.children:
for child in node.children:
choices.append((child.id, f"-{child.value}"))
if child.children:
for c in child.children:
choices.append((c.id, f"--{c.value}"))
return choices
我目前正在处理的代码
def get_choices():
c = Node.query.filter_by(parent_id=None).all()
return _get_choices(c)
def _get_choices(children, depth=0, prev_choices=[]):
new_choices = prev_choices
for child in children:
new_choices.append((child.id, f"{depth * '-'}{child.value}"))
if child.children:
_get_choices(child.children, depth+1, new_choices)
return new_choices
【问题讨论】:
-
非常感谢,它帮助我解决了我的问题。