pythonpython-3.xpython-2.7networkxjsnetworkx

How to find node parents information in NetworkX?


I have a NetworkX graph like following.

g = nx.DiGraph()
g.add_edge('a', 'b')
g.add_edge('b', 'c')
g.add_edge('b', 'd')
g.add_edge('b', 'e')
g.add_edge('e', 'f')

I have a Python function called getHop and it takes two parameters. One is node and other one is hop.

getHop(node, hop):

If node is f and hop is 1 then getHop should return parent node(s) of f. In this case it is e.

If node is f and hop is 2 then getHop should return grand parent node(s) of f. In this case it is b.

If node is f and hop is 3 then getHop should return great grandparent node(s) of f. In this case it is a.

How can I implement the above-mentioned scenario in NetworkX. Please let me know. Thanks in advance.


Solution

  • I am not aware of a function in the networkx library that allows you to do that but it should be fairly straight forward to build through a loop in a function, see example below that should yield your result:

    Keep in mind that the predecessors function returns an iterator so it was simpler to insert the result of the function in a list and obtain the first value https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.DiGraph.predecessors.html

    def getHop(node, hop):
        if hop == 1: 
            result = list(g.predecessors(node))[0]
        else: 
            for hop_element in range(hop): 
                if hop_element == 0: 
                    temp_result = list(g.predecessors(node))[0]
                elif hop_element +1 == hop:
                    result = list(g.predecessors(temp_result))[0]
                else: 
                    temp_result = list(g.predecessors(temp_result))[0]
        return result