開始使用免費開始

另一側分區的共用節點

為了建立你對推薦系統的概念,我們先從基礎開始。這裡的重點是計算二分圖中使用者之間的相似度。

你的任務是撰寫一個函式,接受兩個節點,並回傳兩個使用者節點之間共用的儲存庫節點集合。

在本練習中,你會用到以下方法與函式:.neighbors()set().intersection(),以及你將定義的 shared_partition_nodes 函式。

本練習屬於課程

Python 網路分析進階

檢視課程

練習說明

  • 撰寫名為 shared_partition_nodes() 的函式,接受 3 個引數——圖 Gnode1node2——並回傳 node1node2 之間共用的節點集合。
    • 使用 assert 陳述式與 'bipartite' 欄位檢查 node1node2 是否屬於同一個分區。
    • 取得 node1 的鄰居並存為 nbrs1
    • 取得 node2 的鄰居並存為 nbrs2
  • 使用集合的 .intersection() 方法計算 nbrs1nbrs2 的重疊。
  • 使用你寫的 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(____(____))
編輯並執行程式碼