开始使用免费开始使用

查找开三角

现在来查找开三角吧!回忆一下,它们是好友推荐系统的基础:如果 "A" 认识 "B",且 "A" 也认识 "C",那么很可能 "B" 也认识 "C"。

本练习是课程的一部分

Python 网络分析入门

查看课程

练习说明

  • 编写函数 node_in_open_triangle(),包含两个参数 Gn,用于判断节点是否与其邻居构成一个"开三角"。
    • for 循环中,遍历所有可能的三角关系组合。
    • 如果节点 n1n2 之间没有边,则将 in_open_triangle 设为 True,跳出该 if 分支并返回 in_open_triangle
  • 使用该函数统计 T 中存在的开三角数量。
    • for 循环中,遍历 T 中的所有节点。
    • 如果当前节点 n 位于一个开三角中,则将 num_open_triangles 加 1。

交互式实操练习

通过完成这段示例代码来试试这个练习。

from itertools import combinations

# Define node_in_open_triangle()
def node_in_open_triangle(G, n):
    """
    Checks whether pairs of neighbors of node `n` in graph `G` are in an 'open triangle' relationship with node `n`.
    """
    in_open_triangle = False

    # Iterate over all possible triangle relationship combinations
    for n1, n2 in ____:

        # Check if n1 and n2 do NOT have an edge between them
        if not ____:

            in_open_triangle = ____

            break

    return ____

# Compute the number of open triangles in T
num_open_triangles = 0

# Iterate over all the nodes in T
for n in ____:

    # Check if the current node is in an open triangle
    if ____:

        # Increment num_open_triangles
        ____ += 1

print(num_open_triangles)
编辑并运行代码