開始使用免費開始

找出開放三角形

現在來找找開放三角形吧!回想一下,它們是朋友推薦系統的基礎:如果「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

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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)
編輯並執行程式碼