递归函数,用于返回祖先和后继者之间的行



我需要编写一个递归函数,如果存在祖先和继承者之间的行,则返回该函数。该函数以祖先、继承者和儿童及其父母的字典为参数。我目前拥有的代码在某些情况下有效,但并非适用于所有情况,因此其中一定还缺少一些东西。我目前尝试使用列表来添加人员姓名,但最终我需要以某种方式将它们一一打印出来。这就是我所拥有的和例子。前 4 个有效,但最后 3 个无效。在查看第一个示例时,基本上它需要返回的是

Lucia
Adele
Sam
John
table = {'John': ('Sam', 'Mary'),
'Mary': ('Konstantin', 'Marie'),
'Rita': ('Sam', 'Mary'),
'Simon': ('Sam', 'Mary'),
'Marie': ('Carl', 'Liz'),
'Sam': ('Joseph', 'Adele'),
'Adele': ('Johannes', 'Lucia'),
'Konstantin': ('Viktor', 'Jelena'),
'Joseph': ('August', 'Emma'),
'Viktor': ('Nikolai', 'Maria')}
def return_line(ancestor, successor, table, line = []):
if successor in table:
parents = table[successor]
if ancestor in parents:
if ancestor not in line:
line.append(ancestor)
if successor not in line:
line.append(successor)         
else:
successor_1 = parents[0]
successor_2 = parents[1]
return_line(ancestor, successor_1, table)
if line == []:
return_line(ancestor, successor_2, table)
else:
ancestor = line[-1]
return_line(ancestor, successor, table)            
else:
return
if line != []:
return line
else:
return("Doesn't exist")
print(return_line("Lucia", "John", table))
print(return_line("Marie", "Adele", table))
print(return_line("Maria", "Mary", table))
print(return_line("Emma", "Rita", table))
print(return_line("Nikolai", "John", table))
print(return_line("Jelena", "John", table))
print(return_line("Carl", "Mary", table))

一个更简单的实现,无需传递可变参数:

def line(ancestor, successor, table):
if ancestor == successor:
return [successor]
if successor not in table:
return  # no line exists
for parent in table[successor]:
anc_line = line(ancestor, parent, table)
if anc_line:
return anc_line + [successor] 
line("Lucia", "John", table)
# ['Lucia', 'Adele', 'Sam', 'John']
line("Marie", "Adele", table)
# None
line("Maria", "Mary", table)
# ['Maria', 'Viktor', 'Konstantin', 'Mary']
line("Emma", "Rita", table)
# ['Emma', 'Joseph', 'Sam', 'Rita']
line("Nikolai", "John", table)
# ['Nikolai', 'Viktor', 'Konstantin', 'Mary', 'John']
line("Jelena", "John", table)
# ['Jelena', 'Konstantin', 'Mary', 'John']
line("Carl", "Mary", table)
# ['Carl', 'Marie', 'Mary']

基本情况:
1.ancestor == successor:一个人构成单例线
2。successor not in table:没有关于这个人父母的更多信息,所以没有必要再看下去了

递归:
1.找到从祖先到父级
任一方的一条线 2.如果存在,请附加手头的人

最新更新