bipartite 關鍵字
在影片中,Eric 介紹了 'bipartite' 關鍵字。這個關鍵字是節點中繼資料(metadata)字典的一部分,既可以在新增節點時指定,也可以在節點加入後再指定。不過要記得,根據定義,在二分圖中,節點不能與同一個分區中的其他節點相連。
在這裡,你要撰寫一個函式,回傳二分圖中指定分區的所有節點。本題所用的 GitHub 二分圖的相關分區為 'projects' 與 'users'。
本練習屬於課程
Python 網路分析進階
練習說明
- 撰寫一個名為
get_nodes_from_partition()的函式,接受兩個引數——二分圖G與G的某個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(____(____))