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

Subgraph I

บางครั้งอาจต้องการวิเคราะห์เฉพาะโหนดบางส่วนในเครือข่าย ทำได้โดยคัดลอกโหนดเหล่านั้นออกมาเป็น graph object ใหม่ ด้วยคำสั่ง G.subgraph(nodes) ซึ่งจะคืนค่าเป็น graph object ใหม่ (ชนิดเดียวกับ graph ต้นฉบับ) ที่ประกอบด้วยโหนดจาก iterable ของ nodes ที่ส่งเข้าไป

ได้นำเข้า matplotlib.pyplot ให้แล้วในชื่อ plt

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

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

ดูคอร์ส

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

  • เขียนฟังก์ชัน get_nodes_and_nbrs(G, nodes_of_interest) เพื่อดึง subgraph จาก graph G ที่ประกอบด้วย nodes_of_interest และ neighbors ของโหนดเหล่านั้น
    • ในลูป for แรก ให้วนซ้ำผ่าน nodes_of_interest และเพิ่มโหนดปัจจุบัน n เข้าไปใน nodes_to_draw
    • ในลูป for ที่สอง ให้วนซ้ำผ่าน neighbors ของ n และเพิ่ม neighbor ทุกตัว nbr เข้าไปใน nodes_to_draw
  • ใช้ฟังก์ชันนี้เพื่อดึง subgraph จาก T ที่ประกอบด้วยโหนด 29, 38 และ 42 (ซึ่งอยู่ในลิสต์ nodes_of_interest ที่กำหนดไว้แล้ว) พร้อมด้วย neighbors ของโหนดเหล่านั้น แล้วบันทึกผลลัพธ์เป็น T_draw
  • วาด subgraph 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()
แก้ไขและรันโค้ด