I want to obtain directly dependent nodes of the given node, if possible.
For example, on the following example nx.ancestors(G, 5)
returns {0, 1, 2, 3, 4}
, these nodes are iteratively dependent on node 5
. But I want to obtain {3, 4}
, where these nodes are directly connected to node 5
.
Also, nx.descendants(G, 0)
returns {1, 2, 3, 4, 5}
, where I want to obtain {1, 2}
that are directly connected to node 0
.
import networkx as nx
import matplotlib.pyplot as plt
g = nx.Graph()
G = nx.DiGraph()
# add 5 nodes, labeled 0-4:
map(G.add_node, range(5))
# 1,2 depend on 0:
G.add_edge(0,1)
G.add_edge(0,2)
# 3 depends on 1,2
G.add_edge(1,3)
G.add_edge(2,3)
# 4 depends on 1
G.add_edge(1,4)
# 5 depends on 3 and 4
G.add_edge(3,5)
G.add_edge(4,5)
print(nx.ancestors(G, 5))
print(nx.descendants(G, 0))
Output:
{0, 1, 2, 3, 4}
{1, 2, 3, 4, 5}
You can use
predecessors
andsuccessors
:Output:
And,
Output: