
232
똑똑한 코드 작성을 위한 실전 알고리즘
for i in range(2, 6):
G.add_edge('B{}'.format(i), 'C{}'.format(i))
➏
if 2 < i < 5:
G.add_edge('B{}'.format(i), 'B{}'.format(i+1))
if i < 5:
G.add_edge('C{}'.format(i), 'C{}'.format(i+1))
>>> print(G.number_of_nodes(), 'nodes.')
➐
>>> print(G.number_of_edges(), 'edges.')
>>> print('adjacent nodes to C3:', list(G['C3']))
➑
>>> print('edges adjacent to C3:', list(G.edges('C3')))
➒
12 nodes.
12 edges.
adjacent nodes to C3: ['C2', 'B3', 'C4']
edges adjacent to C3: [('C3', 'C2'), ('C3', 'B3'), ('C3', 'C4')]
➊
nx.Graph()
는 무향 그래프를 새로 생성한다.
➋
노드는
None
을 제외한 모든 해시 가능한 파이썬 객체가 될 수 있다. 문자열도 좋다.
➌
add_nodes_from()
을 사용해 리스트에서 여러 노드를 추가한다.
➍
add_edge(u, ...