Reputation: 31
I'm working on a function that creates a family tree using a directed graph in networkx, where the nodes are family members with the date of birth as a node attribute. Now what i want to do is to make another function that given the graph G and a name of a node, returns a sorted list of all the "grandsons" of that node. So basically, i do this:
return sort(G.successors(G.successors(node)))
But since G.successors
returns a list of the successors, this doesn't work.
How would you approach this?
Thanks!
Upvotes: 3
Views: 1461
Reputation: 4882
You can write your own function for this task. If you are sure your DiGraph
is a tree, you can replace the set()
with a list
. Please also add a minimal reproducible example with the desired output in your next questions.
import networkx as nx
family_tree = nx.DiGraph()
family_tree.add_edges_from([("GP", "P1"), ("GP", "P2"), ("P1", "S1"), ("S1", "GS1"), ("P1", "S2")])
def successors_of_successors(graph, node):
results = set()
for successor in graph.successors(node):
results.update(graph.successors(successor))
return results
print(successors_of_successors(family_tree, "GP"))
# {'S2', 'S1'}
print(successors_of_successors(family_tree, "P1"))
# {'GS1'}
Upvotes: 1