1 # Filename: youxiangtu.py
2
3 # NetworkX
4 import networkx as nx
5
6 # establish a null undirected graphy
7 G = nx.Graph() # directed graphy: G = nx.DiGraph()
8 # add node1
9 G.add_node(1)
10 # add edge2-3(also add node2 node3)
11 G.add_edge(2, 3)
12 # add edge3-2
13 G.add_edge(3, 2) # undirected graphy, edge2-3 & edge3-2 is the same
14
15 print G.nodes() # output all nodes: [1, 2, 3]
16 print G.edges() # output all edges: [(2, 3)]
17 print G.number_of_edges() # output the count of edges: 1
18
19 # weighted graphy
20 # add edge0-1, edge1-2, which weighted 3.0 & 7.5
21 G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
22 # output the weight of edge1-2: {'weght': 7.5}
23 print G.get_edge_data(1, 2)
24
25 # calculate the shortest pathes for the graphy G
26 path = nx.all_pairs_shortest_path(G)
27 print path[0][2] # output the shortest path between node0 & node2: [0,1, 2]