開始使用免費開始

bipartite 關鍵字

在影片中,Eric 介紹了 'bipartite' 關鍵字。這個關鍵字是節點中繼資料(metadata)字典的一部分,既可以在新增節點時指定,也可以在節點加入後再指定。不過要記得,根據定義,在二分圖中,節點不能與同一個分區中的其他節點相連。

在這裡,你要撰寫一個函式,回傳二分圖中指定分區的所有節點。本題所用的 GitHub 二分圖的相關分區為 'projects''users'

本練習屬於課程

Python 網路分析進階

檢視課程

練習說明

  • 撰寫一個名為 get_nodes_from_partition() 的函式,接受兩個引數——二分圖 GG 的某個 partition——並只回傳該 partition 的節點。
    • 使用 for 迴圈迭代 G 的所有節點(不包含中繼資料)。
    • 存取目前節點的中繼資料字典中的 'bipartite' 關鍵字。若其值等於 partition,就把目前節點加入清單 nodes
  • 將你寫的 get_nodes_from_partition() 搭配 len() 使用,以:
    • 印出 G'projects' 分區節點數量。
    • 印出 G'users' 分區節點數量。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Define get_nodes_from_partition()
def ____:
    # Initialize an empty list for nodes to be returned
    nodes = []
    # Iterate over each node in the graph G
    for n in ____:
        # Check that the node belongs to the particular partition
        if G.nodes[n]['____'] == ____:
            # If so, append it to the list of nodes
            ____
    return nodes

# Print the number of nodes in the 'projects' partition
print(____(get_nodes_from_partition(____, '____')))

# Print the number of nodes in the 'users' partition
print(____(____))
編輯並執行程式碼