0

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.

VIVEK
  • 107
  • 1
  • 9
  • can you also provide some sample data for the arguments of ` lowestcommonancestor` ? – rocksportrocker Sep 20 '18 at 12:26
  • If you have the root-to-leaf path (as is implied from that you have asked about that before) for both words, then you can just start at the root of both and then continue down the tree as long as the nodes don't diverge. – JohanL Sep 20 '18 at 15:28
  • @rocksportrocker I updated the question. Please let me know if there is any other issue. – VIVEK Sep 20 '18 at 17:13
  • @JohanL It might not be a binary tree as well. – VIVEK Sep 20 '18 at 17:13

0 Answers0