查找开三角
现在来查找开三角吧!回忆一下,它们是好友推荐系统的基础:如果 "A" 认识 "B",且 "A" 也认识 "C",那么很可能 "B" 也认识 "C"。
本练习是课程的一部分
Python 网络分析入门
练习说明
- 编写函数
node_in_open_triangle(),包含两个参数G和n,用于判断节点是否与其邻居构成一个"开三角"。- 在
for循环中,遍历所有可能的三角关系组合。 - 如果节点
n1和n2之间没有边,则将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)