14 精币
各位老师,下午好,麻烦哪位老师有空将这段python代码用易语言 写出来,不胜感激,是一个和并查集有关的。
class Person:
def __init__ (self , name):
self .name = name
self .children = []
def add_child (self , child):
self .children.append(child)
def __str__ (self , level=0 ):
result = ' ' * level * 2 + self .name + ' \n '
for child in self .children:
result += child.__str__ (level + 1 )
return result
class FamilyTree:
def __init__ (self ):
self .members = {}
def get_or_create_person (self , name):
if name not in self .members:
self .members[name] = Person(name)
return self .members[name]
def add_relationship (self , parent_name, child_name):
parent = self .get_or_create_person(parent_name)
child = self .get_or_create_person(child_name)
parent.add_child(child)
def display_tree (self ):
# 找到根节点(没有父亲的节点)
all_children = {child.name for person in self .members.values() for child in person.children}
roots = [person for name, person in self .members.items() if name not in all_children]
result = ""
for root in roots:
result += str (root)
return result
# 示例数据
relationships = [
("BOM" , "1" ),
("BOM" , "2" ),
("BOM" , "3" ),
("1" , "11" ),
("1" , "12" ),
("1" , "13" ),
("2" , "21" ),
("3" , "31" ),
("31" , "311" ),
("31" , "312" ),
("312" , "3121" )
]
# 创建族谱实例
family_tree = FamilyTree()
# 添加父子关系
for parent, child in relationships:
family_tree.add_relationship(parent, child)
# 显示族谱
print (" 族谱: " )
print (family_tree.display_tree())
下载
资源
0
我来回答