找出開放三角形
現在來找找開放三角形吧!回想一下,它們是朋友推薦系統的基礎:如果「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。
- 在
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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)