找出參與三角形的節點
NetworkX 提供一個可計算每個節點參與多少個三角形的 API:nx.triangles(G)。它會回傳一個以節點為鍵、三角形數量為值的字典。你在本練習的工作是修改先前定義的函式,從給定的節點出發,擷取所有與之形成三角關係的節點。
本練習屬於課程
Python 網路分析入門
練習說明
- 撰寫函式
nodes_in_triangle(),包含兩個參數G與n,用來找出與給定節點呈三角關係的所有節點。- 在
for迴圈中,遍歷所有可能的三角關係組合。 - 檢查節點
n1和n2之間是否有邊。如果有,將兩個節點都加入集合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(____(____, ____)) == ____