เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

Shortest Path III

นี่คือแบบฝึกหัดสุดท้ายของชุดนี้! ขั้นตอนนี้จะเป็นการเขียนโค้ดเพื่อให้ฟังก์ชันคืนค่า False เมื่อไม่มีเส้นทางเชื่อมระหว่างโหนดสองโหนด

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การวิเคราะห์เครือข่ายเบื้องต้นด้วย Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • ตรวจสอบว่า queue ถูกใช้จนหมดแล้วหรือไม่ โดยดูที่ element สุดท้ายของ queue ด้วย [-1]
  • ใส่ return statement ที่เหมาะสมเพื่อระบุว่ามีเส้นทางระหว่างโหนดทั้งสองหรือไม่

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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 = list(G.neighbors(node))
        if node2 in neighbors:
            print('Path exists between nodes {0} and {1}'.format(node1, node2))
            return True
            break

        else:
            visited_nodes.add(node)
            queue.extend([n for n in neighbors if n not in visited_nodes])

        # Check to see if the final element of the queue has been reached
        if node == ____:
            print('Path does not exist between nodes {0} and {1}'.format(node1, node2))

            # Place the appropriate return statement
            return ____
แก้ไขและรันโค้ด