开始使用免费开始使用

为尚未共同编辑的协作者做推荐

最后,您将利用开放三角形的概念,为 GitHub 用户推荐潜在的合作对象!

本练习是课程的一部分

Python 网络分析入门

查看课程

练习说明

  • 汇总一份应互相推荐合作的 GitHub 用户列表。具体步骤:
    • 在第一个 for 循环中,遍历 G 中的所有节点,并包含元数据(通过设置 data=True)。
    • 在第二个 for 循环中,遍历所有可能的三角形组合,可使用 size2combinations() 函数来获取。
    • 如果 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)
编辑并运行代码