Lowest common ancestor on dependency parsed tree

179 views Asked by At

I am seeing this similar post: How to make a tree from the output of a dependency parser? where people helped me to get the root-to-leaf path. I wanted to find the lowest common ancestor of two words since I want to find the path between two nodes.

Till now, I have this:

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

categories:

[{'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'}]}]}]

When I call lowestcommonancestor(categories,'fuck','U'), I get week which is a parent of U but not fuck. Hence, I should get arrested as the node.

I am not able to complete the function and I think I am not returning the correct node. Kindly help.

0

There are 0 answers