另一側分區的共用節點
為了建立你對推薦系統的概念,我們先從基礎開始。這裡的重點是計算二分圖中使用者之間的相似度。
你的任務是撰寫一個函式,接受兩個節點,並回傳兩個使用者節點之間共用的儲存庫節點集合。
在本練習中,你會用到以下方法與函式:.neighbors()、set()、.intersection(),以及你將定義的 shared_partition_nodes 函式。
本練習屬於課程
Python 網路分析進階
練習說明
- 撰寫名為
shared_partition_nodes()的函式,接受 3 個引數——圖G、node1、node2——並回傳node1與node2之間共用的節點集合。- 使用 assert 陳述式與
'bipartite'欄位檢查node1與node2是否屬於同一個分區。 - 取得
node1的鄰居並存為nbrs1。 - 取得
node2的鄰居並存為nbrs2。
- 使用 assert 陳述式與
- 使用集合的
.intersection()方法計算nbrs1與nbrs2的重疊。 - 使用你寫的
shared_partition_nodes()搭配len(),列印使用者'u7909'與'u2148'之間共用的儲存庫數量。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def ____:
# Check that the nodes belong to the same partition
assert G.nodes[____]['bipartite'] == G.nodes[____]['bipartite']
# Get neighbors of node 1: nbrs1
nbrs1 = ____
# Get neighbors of node 2: nbrs2
nbrs2 = ____
# Compute the overlap using set intersections
overlap = ____(____).____(____)
return overlap
# Print the number of shared repositories between users 'u7909' and 'u2148'
print(____(____))