【问题标题】:Save descendence in family tree with a recursive function in Python在 Python 中使用递归函数保存家谱中的后代
【发布时间】:2021-11-27 10:18:53
【问题描述】:

我有一本家谱字典,其中孩子的名字作为键,他们的爸爸和妈妈的名字在列表中作为值。

d = { 
'Kevin': ('Tom', 'Marge'), 
'Marge': ('John', 'Mary'), 
'Elle': ('Tom', 'Marge'), 
'Seth': ('Tom', 'Marge'), 
'Mary': ('Carl', 'Elena'), 
'Tom': ('Joseph', 'Alice'), 
'Alice': ('Rob', 'Amy'), 
'John': ('James', 'Elena'), 
'Joseph': ('Adam', 'Emma'), 
'James': ('Nick', 'Maria') }

我需要编写一个递归函数,以便在两个人之间存在下降时返回 True。如果有后代,它必须打印出关系链,即:

>>> print("Is there a lineage?", lineage('Amy', 'Kevin', d))
Amy
Alice
Tom
Kevin
Is there a lineage? True

否则如果没有:

>>> print("Is there a lineage?", lineage('Mary', 'Alice', d))
Is there a lineage? False

这是我到目前为止所得到的。它似乎始终如一地返回 True 或 False,但我在弄清楚如何保存两个人之间的路径时遇到了麻烦。

line = []

def lineage(parent, child, d):
    dad, mom = d[child][0], d[child][1]
    
    try:
        if parent in d[child]:
            line.append(parent)
        else:
            try:
                lineage(parent, dad, d)
            except:
                lineage(parent, mom, d)
        
        return True
    
    except:
        return False

我是递归的新手,因此非常感谢任何有关如何解决此问题的想法或帮助。

【问题讨论】:

    标签: dictionary recursion family-tree


    【解决方案1】:
    • 当路径存在时,我让您的函数返回路径,而不是 True
    • 我建议在此处避免使用try / except

    确实,尝试访问d[child] 而不检查child 是否在d 中可能会导致异常。但是,这是递归的基本情况;如果在函数的开头使用显式的if 明确标识基本情况,而不是在函数的末尾没有任何解释的晦涩的“发生某些异常”,那么您的代码将更容易理解。

    def lineage(parent, child, d):
        if parent == child:
            return [child]
        elif child not in d:
            return False
        else:
            dad, mom = d[child][0], d[child][1]
            path_via_dad = lineage(parent, dad, d)
            if path_via_dad:
                path_via_dad.append(child)
                return path_via_dad
            else:
                path_via_mom = lineage(parent, mom, d)
                if path_via_mom:
                    path_via_mom.append(child)
                    return path_via_mom
                else:
                    return False
    

    这里有一个更短的等价版本,依赖于python中逻辑运算符or的具体行为:

    def lineage(parent, child, d):
        if parent == child:
            return [child]
        elif child not in d:
            return False
        else:
            dad, mom = d[child][0], d[child][1]
            path = lineage(parent, dad, d) or lineage(parent, mom, d)
            if path:
                path.append(child)
            return path
    

    测试:

    >>> lineage('Amy', 'Kevin', d)
    ['Amy', 'Alice', 'Tom', 'Kevin']
    >>> lineage('Mary', 'Alice', d)
    False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2023-03-08
      • 1970-01-01
      • 2018-06-24
      相关资源
      最近更新 更多