시작하기무료로 시작하기

삼각관계에 포함된 노드 찾기

NetworkX는 각 노드가 포함된 삼각형의 개수를 세는 API nx.triangles(G)를 제공합니다. 이 함수는 노드를 키로, 삼각형 개수를 값으로 갖는 딕셔너리를 반환합니다. 이 연습 문제에서는 앞서 정의한 함수를 수정하여, 주어진 노드와 삼각관계를 이루는 모든 노드를 추출하도록 하시면 됩니다.

이 연습은 강의의 일부입니다

Python으로 시작하는 네트워크 분석

강의 보기

연습 안내

  • 두 개의 매개변수 Gn을 받아 주어진 노드와 삼각관계에 있는 모든 노드를 찾는 함수 nodes_in_triangle()을(를) 작성하세요.
    • for 루프에서 가능한 모든 삼각관계 조합을 순회하세요.
    • 노드 n1n2 사이에 간선이 있는지 확인하세요. 있다면 두 노드를 집합 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(____(____, ____)) == ____
코드 편집 및 실행