0

我看到了类似的帖子:如何从依赖解析器的输出中生成树?人们帮助我获得了从根到叶的路径。我想找到两个单词的最低共同祖先,因为我想找到两个节点之间的路径。

到目前为止,我有这个:

def lowestcommonancestor(categories,p,q):
    for category in categories:
        if category['Name']==p or category['Name']==q or category['Name']==None:
            return category
        if 'children' in category:
            node1=lowestcommonancestor(category['children'],p,q)
            if node1 is not None: #to see if the other word is present as a child
                if 'children' in node1:
                    node2=lowestcommonancestor(node1['children'],p,q)
                    if node2 is not None:
                        return node1
                else:# if not then we need to return the root
                    return category
    return None

类别:

[{'Name': 'arrested', 'Relationship': 'ROOT', 'children': [{'Name': 'week', 'Relationship': 'nmod:tmod', 'children': [{'Name': 'U', 'Relationship': 'compound'}, {'Name': 'smoke', 'Relationship': 'compound'}]}, {'Name': 'you', 'Relationship': 'nsubjpass'}, {'Name': 'could', 'Relationship': 'aux'}, {'Name': 'be', 'Relationship': 'auxpass'}, {'Name': 'fuck', 'Relationship': 'dobj', 'children': [{'Name': 'U', 'Relationship': 'compound'}, {'Name': 'dumb', 'Relationship': 'amod'}]}]}]

当我打电话时lowestcommonancestor(categories,'fuck','U'),我得到week了哪个是U但不是的父母fuck。因此,我应该arrested作为节点。

我无法完成该功能,并且我认为我没有返回正确的节点。请帮忙。

4

0 回答 0