我需要有关家谱递归表示的帮助。数据如下:
children_and_parents = {
"Mary": ["Patricia", "Lisa"],
"Patricia": ["Barbara", "Helen", "Maria"],
"Maria": ["Keren", "Carol"],
"Barbara": ["Betty"]
}
我需要提到这些值是对象,因此我需要调用它们 children_and_parents["Maria"].child
来获取 ['Patricia', 'Lisa']
.
我目前拥有的递归程序:
def draw_family_tree(person, level=0):
if person in children_and_parents:
for i in range (len(children_and_parents[person].child)):
print (" "*level, person)
return draw_family_tree(children_and_parents[person].child[i], level+3)
它目前正在做的是:
Mary
Patricia
Barbara
但结果应该是这样的:
Mary
Patricia
Barbara
Betty
Helen
Maria
Keren
Carol
Lisa
我被困在程序的开头。如果有人愿意提供帮助,我将非常感激。
最佳答案
查找树的根是单独操作的一个很好的选择。在您的示例中,我们知道它是 "Mary"
,因此我们可以进行相应的迭代。如果未知,您可以编写一个函数来返回不是任何其他节点的子节点的第一个父节点:
def find_root(tree):
all_children = {x for y in tree.values() for x in y}
for node in tree:
if node not in all_children:
return node
至于实际的打印过程,请在迭代子节点之前尝试打印父节点。我还建议将树作为参数传递给函数以维护封装并使其可重用(即不依赖于调用范围中存在的某个名为 children_and_parents
的变量)。
def draw_family_tree(tree, root, gap=3, level=0):
if root:
print(" " * level + root)
if root in tree:
for child in tree[root]:
draw_family_tree(tree, child, gap, level + gap)
我们还可以避免draw_family_tree
中的副作用。并让它返回一个生成器,让调用者决定如何处理结果:
def find_root(tree):
all_children = {x for y in tree.values() for x in y}
for node in tree:
if node not in all_children:
return node
def draw_family_tree(tree, root, gap=3, level=0):
if root:
yield " " * level + root
if root in tree:
for child in tree[root]:
yield from draw_family_tree(tree, child, gap, level + gap)
if __name__ == "__main__":
children_and_parents = {
"Mary": ["Patricia", "Lisa"],
"Patricia": ["Barbara", "Helen", "Maria"],
"Maria": ["Keren", "Carol"],
"Barbara": ["Betty"]
}
root = find_root(children_and_parents)
for node in draw_family_tree(children_and_parents, root):
print(node)
输出:
Mary
Patricia
Barbara
Betty
Helen
Maria
Keren
Carol
Lisa
正如前面的讨论中提到的,我不建议使用类来实现简单的 <string, list>
一对;它增加了很多没有功能的冗长内容,实际上有点误导,因为 parent
表明该人有一个 parent (它实际上指的是该对象所代表的人的名字)。如果您确实选择走这条路线,则需要附加 .child
到所有括号访问并写入 __repr__(self)
您的类(class)的函数(或 print(root.parent)
。
关于python - 使用对象递归打印家谱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53505454/