三角形に関与するノードを見つける
NetworkX には、各ノードが関与する三角形の数を数えるための API nx.triangles(G) があります。これは、キーがノード、値が三角形の数のディクショナリを返します。この演習では、前に定義した関数を拡張して、指定したノードと三角関係にあるすべてのノードを取り出せるようにしてください。
この演習はコースの一部です
Pythonで学ぶネットワーク分析入門
演習の手順
Gとnの2つの引数を取り、指定したノードと三角関係にあるすべてのノードを特定する関数nodes_in_triangle()を作成します。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(____(____, ____)) == ____