計算每個節點的鄰居數
要如何判斷一個節點是否重要?有好幾種方式可用。這裡要看的一個指標是:某個節點擁有的鄰居數量。
每個 NetworkX 圖形 G 都提供 .neighbors(n) 方法,會回傳節點 n 的鄰居節點迭代器。先在 IPython Shell 中對 Twitter 網路 T 使用這個方法,取得節點 1 的鄰居。這能讓你熟悉此方法的運作方式。接著,你在本練習的工作是撰寫一個函式,回傳所有擁有 m 個鄰居的節點。
本練習屬於課程
Python 網路分析入門
練習說明
- 撰寫名為
nodes_with_m_nbrs()的函式,包含兩個參數G與m,並回傳所有擁有m個鄰居的節點。作法如下:- 迭代
G中的所有節點(不包含中繼資料)。 - 搭配使用
len()、list()與.neighbors()方法,計算圖G中節點n的鄰居總數。- 若節點
n的鄰居數等於m,使用.add()方法將n加入集合nodes。
- 若節點
- 迭代完
G的所有節點後,回傳集合nodes。
- 迭代
- 使用你撰寫的
nodes_with_m_nbrs()函式,找出圖T中所有擁有 6 個鄰居的節點。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define nodes_with_m_nbrs()
def ____:
"""
Returns all nodes in graph G that have m neighbors.
"""
nodes = set()
# Iterate over all nodes in G
for n in ____:
# Check if the number of neighbors of n matches m
if ____ == ____:
# Add the node n to the set
____
# Return the nodes with m neighbors
return nodes
# Compute and print all nodes in T that have 6 neighbors
six_nbrs = ____
print(____)