शुरू करेंमुफ़्त में शुरू करें

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 हैं. iterable neighbors का iterator है, और conditional यह है कि यदि n visited nodes में हो.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

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 ____])
कोड संपादित करें और चलाएँ