I've been trying to write a recursive function for the below code example but the issue im facing is that my loop gets double up in value the next time I run it.
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
the code im currently working on
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