Shortest Path II
अब जब आपने यह कोड लिख लिया है कि destination नोड neighbors में मौजूद है या नहीं, तो अगला कदम है उसी फंक्शन को बढ़ाते हुए उस स्थिति के लिए कोड लिखना जहाँ destination नोड neighbors में मौजूद नहीं है.
आपको सारा कोड else कंडीशन में लिखना है; यानी तब, जब node2 neighbors में न हो.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में नेटवर्क विश्लेषण का परिचय
अभ्यास निर्देश
.add()मेथड का उपयोग करके, वर्तमान नोडnodeकोvisited_nodesसेट में जोड़ें ताकि किन नोड्स को पहले ही विज़िट किया जा चुका है, उसका ट्रैक रहे.- वर्तमान नोड
nodeके उन neighbors कोqueueमें जोड़ें जिन्हें अभी तक विज़िट नहीं किया गया है. ऐसा करने के लिए, आपकोqueueकी.extend()मेथड को list comprehension के साथ उपयोग करना होगा..extend()मेथड दी गई लिस्ट के सभी items को append करती है.- list comprehension का output expression और iterator variable दोनों
nहैं. iterableneighborsका iterator है, और conditional यह है कि यदिnvisited nodes में न हो.
- list comprehension का output expression और iterator variable दोनों
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
def path_exists(G, node1, node2):
"""
This function checks whether a path exists between two nodes (node1, node2) in graph G.
"""
visited_nodes = set()
queue = [node1]
for node in queue:
neighbors = G.neighbors(node)
if node2 in neighbors:
print('Path exists between nodes {0} and {1}'.format(node1, node2))
return True
else:
# Add current node to visited nodes
____
# Add neighbors of current node that have not yet been visited
queue.extend([____ for ____ in ____ if ____ not in ____])