開始使用免費開始

推薦尚未共同編輯過的協作者

最後,來運用開放三角形的概念,為 GitHub 使用者推薦合作夥伴!

本練習屬於課程

Python 網路分析入門

檢視課程

練習說明

  • 彙整一份應相互推薦合作的 GitHub 使用者清單。作法如下:
    • 在第一個 for 迴圈中,迭代 G 中的所有節點,並包含中繼資料(設定 data=True)。
    • 在第二個 for 迴圈中,迭代所有可能的三角形組合,可用 combinations() 並將 size 設為 2 來取得。
    • n1n2 之間沒有邊,表示應該推薦這兩個節點(使用者)合作,因此在此情況下將 recommended 字典中 (n1), (n2) 的值加一。你可以用 .has_edge() 方法檢查 n1n2 是否存在邊。
  • 使用串列生成式找出最應被推薦合作的前 10 組使用者配對。可迭代物件 應為 recommended 字典的鍵值對(可用 .items() 取得),而條件則是在 count 大於 all_counts 的前 10 名門檻時成立。注意 all_counts 已依遞增排序,因此你可以用 all_counts[-10] 取得前 10 的下限。

動手互動練習

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

# Import necessary modules
from itertools import combinations
from collections import defaultdict

# Initialize the defaultdict: recommended
recommended = defaultdict(int)

# Iterate over all the nodes in G
for n, d in ____:

    # Iterate over all possible triangle relationship combinations
    for n1, n2 in ____(list(G.neighbors(n)), ____):

        # Check whether n1 and n2 do not have an edge
        if not G.has_edge(____, ____):

            # Increment recommended
            ____[(____, ____)] += 1

# Identify the top 10 pairs of users
all_counts = sorted(recommended.values())
top10_pairs = [pair for pair, count in ____ if ____ > ____]
print(top10_pairs)
編輯並執行程式碼