시작하기무료로 시작하기

하루마다 가장 인기 있는 포럼 찾기: II

이전 연습 문제에서 정말 잘하셨어요. 시간대별 그래프 리스트를 만드는 코드를 작성하셨죠. 이제 그 연습을 마무리해 볼 거예요. 바로 날짜별로 가장 인기 있는 포럼 점수를 받은 포럼이 몇 개인지 알아보겠습니다!

여기서 하실 일 중 하나는 사전을 필터링하는 "딕셔너리 컴프리헨션"입니다. 리스트를 필터링하는 리스트 컴프리헨션과 매우 비슷하지만, 문법은 {key: val for key, val in dict.items() if ...}처럼 생겼다는 점을 기억해 주세요!

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

Python 중급 네트워크 분석

강의 보기

연습 안내

  • G_subforum_nodes를 인수로 하여 nx.bipartite.degree_centrality()로 degree centrality를 구하세요.
  • 사전을 필터링해 포럼의 degree centrality만 남기세요. 출력 표현식의 key: val 쌍은 n, dc여야 합니다. dc.items()를 순회하며 nforum_nodes에 있는지 확인하세요.
  • 가장 인기 있는 포럼(들)을 식별하세요. degree centrality가 가장 높아야 하며(max(forum_dcs.values())), DC 값이 0이면 안 됩니다.
  • 가장 높은 dc 값을 highest_dcs에 추가하세요.
  • 플롯을 만드세요!
    • 첫 번째 플롯은 리스트 컴프리헨션을 사용해 most_popular_forums(리스트의 리스트)를 forums라는 이터레이터 변수로 순회하세요. 출력 표현식은 len()을 사용해 계산한 가장 인기 있는 포럼의 개수여야 합니다.
    • 두 번째 플롯에서는 highest_dcsplt.plot()을 사용해 최고 degree centrality 점수를 시각화하세요.

실습형 인터랙티브 연습

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

# Import necessary modules
from datetime import timedelta
import networkx as nx
import matplotlib.pyplot as plt

most_popular_forums = []
highest_dcs = []
curr_day = dayone 
td = timedelta(days=1)  

while curr_day < lastday:  
    if curr_day.day == 1:  
        print(curr_day)  
    G_sub = nx.Graph()
    G_sub.add_nodes_from(G.nodes(data=True))   
    G_sub.add_edges_from([(u, v, d) for u, v, d in G.edges(data=True) if d['date'] >= curr_day and d['date'] < curr_day + td])
    
    # Get the degree centrality 
    dc = ____
    # Filter the dictionary such that there's only forum degree centralities
    forum_dcs = {____:____ for ____, ____ in ____ if n in ____}
    # Identify the most popular forum(s) 
    most_popular_forum = [n for n, dc in ____ if dc == ____(____) and dc != 0] 
    most_popular_forums.append(most_popular_forum) 
    # Store the highest dc values in highest_dcs
    highest_dcs.append(max(____))
    
    curr_day += td  
    
plt.figure(1) 
plt.plot([len(____) for ____ in ____], color='blue', label='Forums')
plt.ylabel('Number of Most Popular Forums')
plt.show()

plt.figure(2)
plt.plot(____, color='orange', label='DC Score')
plt.ylabel('Top Degree Centrality Score')
plt.show()
코드 편집 및 실행