开始使用免费开始使用

查找参与三角形的节点

NetworkX 提供了一个用于统计每个节点参与三角形数量的 API:nx.triangles(G)。它返回一个字典,键为节点,值为参与的三角形数量。您的任务是基于之前定义的函数,进行修改,以便提取与给定节点构成三角关系的所有节点。

本练习是课程的一部分

Python 网络分析入门

查看课程

练习说明

  • 编写函数 nodes_in_triangle(),包含两个参数 Gn,用于找出与给定节点构成三角关系的所有节点。
    • for 循环中,遍历所有可能的三角关系组合。
    • 检查节点 n1n2 之间是否存在一条边。若存在,将这两个节点都加入集合 triangle_nodes
  • 在一个 assert 语句中使用您编写的函数,检查图 T 中与节点 1 构成三角关系的节点数量是否等于 35

交互式实操练习

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

from itertools import combinations

# Write a function that identifies all nodes in a triangle relationship with a given node.
def nodes_in_triangle(G, n):
    """
    Returns the nodes in a graph `G` that are involved in a triangle relationship with the node `n`.
    """
    triangle_nodes = set([n])

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

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

            # Add n1 to triangle_nodes
            ____

            # Add n2 to triangle_nodes
            ____

    return triangle_nodes

# Write the assertion statement
assert len(____(____, ____)) == ____
编辑并运行代码