Subgraphs I
कई बार ऐसा होगा जब आप केवल नेटवर्क के कुछ नोड्स का ही विश्लेषण करना चाहेंगे। ऐसा करने के लिए, आप उन्हें G.subgraph(nodes) के जरिए किसी दूसरे ग्राफ ऑब्जेक्ट में कॉपी कर सकते हैं। यह एक नया graph ऑब्जेक्ट लौटाता है (मूल ग्राफ के समान प्रकार का) जो पास किए गए nodes के इटेरेबल से बना होता है।
matplotlib.pyplot आपके लिए plt नाम से इम्पोर्ट किया गया है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में नेटवर्क विश्लेषण का परिचय
अभ्यास निर्देश
- एक फंक्शन
get_nodes_and_nbrs(G, nodes_of_interest)लिखें जो ग्राफGसेnodes_of_interestऔर उनके पड़ोसियों से बना सबग्राफ निकालता है.- पहले
forलूप में,nodes_of_interestपर इटरेट करें और मौजूदा नोडnकोnodes_to_drawमें जोड़ें. - दूसरे
forलूप में,nके पड़ोसियों पर इटरेट करें और सभी पड़ोसीnbrकोnodes_to_drawमें जोड़ें.
- पहले
- इस फंक्शन का उपयोग करते हुए
Tसे नोड 29, 38, और 42 (जो पहले से परिभाषित लिस्टnodes_of_interestमें हैं) और उनके पड़ोसियों से बना सबग्राफ निकालें। परिणाम कोT_drawनाम से सेव करें. - सबग्राफ
T_drawको स्क्रीन पर ड्रॉ करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
nodes_of_interest = [29, 38, 42]
# Define get_nodes_and_nbrs()
def get_nodes_and_nbrs(G, nodes_of_interest):
"""
Returns a subgraph of the graph `G` with only the `nodes_of_interest` and their neighbors.
"""
nodes_to_draw = []
# Iterate over the nodes of interest
for n in ____:
# Append the nodes of interest to nodes_to_draw
____
# Iterate over all the neighbors of node n
for nbr in ____:
# Append the neighbors of n to nodes_to_draw
____
return G.subgraph(nodes_to_draw)
# Extract the subgraph with the nodes of interest: T_draw
T_draw = ____
# Draw the subgraph to the screen
____
plt.show()