推薦尚未共同編輯過的協作者
最後,來運用開放三角形的概念,為 GitHub 使用者推薦合作夥伴!
本練習屬於課程
Python 網路分析入門
練習說明
- 彙整一份應相互推薦合作的 GitHub 使用者清單。作法如下:
- 在第一個
for迴圈中,迭代G中的所有節點,並包含中繼資料(設定data=True)。 - 在第二個
for迴圈中,迭代所有可能的三角形組合,可用combinations()並將size設為2來取得。 - 若
n1與n2之間沒有邊,表示應該推薦這兩個節點(使用者)合作,因此在此情況下將recommended字典中(n1), (n2)的值加一。你可以用.has_edge()方法檢查n1與n2是否存在邊。
- 在第一個
- 使用串列生成式找出最應被推薦合作的前 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)