시작하기무료로 시작하기

서브그래프 I

네트워크에서 특정 노드의 부분집합만 분석하고 싶을 때가 있습니다. 이때 G.subgraph(nodes)를 사용해 해당 노드들을 다른 그래프 객체로 복사할 수 있습니다. 이 함수는 전달된 nodes 이터러블로 구성된 새로운 graph 객체(원본 그래프와 동일한 타입)를 반환합니다.

matplotlib.pyplot은 이미 plt로 임포트되어 있습니다.

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

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

강의 보기

연습 안내

  • 그래프 G에서 nodes_of_interest와 그 이웃들로 구성된 서브그래프를 추출하는 함수 get_nodes_and_nbrs(G, nodes_of_interest)를 작성하세요.
    • 첫 번째 for 루프에서는 nodes_of_interest를 순회하며 현재 노드 nnodes_to_draw에 추가하세요.
    • 두 번째 for 루프에서는 n의 이웃을 순회하며 모든 이웃 nbrnodes_to_draw에 추가하세요.
  • 미리 정의된 리스트 nodes_of_interest에 들어 있는 노드 29, 38, 42와 그 이웃들로 구성된 T의 서브그래프를 추출하는 데 이 함수를 사용하세요. 결과를 T_draw로 저장하세요.
  • 서브그래프 T_draw를 화면에 그리세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

nodes_of_interest = [29, 38, 42]

# Define get_nodes_and_nbrs()
def get_nodes_and_nbrs(G, nodes_of_interest):
    """
    Returns a subgraph of the graph `G` with only the `nodes_of_interest` and their neighbors.
    """
    nodes_to_draw = []

    # Iterate over the nodes of interest
    for n in ____:

        # Append the nodes of interest to nodes_to_draw
        ____

        # Iterate over all the neighbors of node n
        for nbr in ____:

            # Append the neighbors of n to nodes_to_draw
            ____

    return G.subgraph(nodes_to_draw)

# Extract the subgraph with the nodes of interest: T_draw
T_draw = ____

# Draw the subgraph to the screen
____
plt.show()
코드 편집 및 실행