python - 使用对象递归打印家谱

标签 python python-3.x object recursion family-tree

我需要有关家谱递归表示的帮助。数据如下:

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

我被困在程序的开头。如果有人愿意提供帮助,我将非常感激。

粗略代码:https://repl.it/repls/BlondCavernousExponents

最佳答案

查找树的根是单独操作的一个很好的选择。在您的示例中,我们知道它是 "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/

相关文章:

python - join() 将当前字符串合并到下一个迭代字符串 :(?

python - 如何在Python中检查没有输入

json - 在 parse.com 类中存储嵌套的 Json

javascript - 使用 Ajax 成功函数遍历返回的对象,输出到表

Python pandas 绘制有间隙的时间序列

python - Django 内置登录系统 - 帐户/个人资料/未找到

python - Django 自定义用户字段与 AbstractBaseUser 冲突

python - 执行器上的 Spark 2.3 内存泄漏

python-3.x - 无法通过cv2.imread()在gcloud的tmp中读取图像,它不返回任何内容

c++ - 当我尝试使用指针打印数组元素时打印垃圾值