1. 程式人生 > >python—networkx:求圖的平均路徑長度並畫出直方圖

python—networkx:求圖的平均路徑長度並畫出直方圖

#!/usr/bin/env python
"""
Compute some network properties for the lollipop graph.
"""
#    Copyright (C) 2004 by
#    Aric Hagberg <[email protected]>
#    Dan Schult <[email protected]>
#    Pieter Swart <[email protected]>
#    All rights reserved.
#    BSD license.

from networkx import *
G = lollipop_graph(4,6)
pathlengths=[]
#單源最短路徑演算法求出節點v到圖G每個節點的最短路徑,存入pathlengths

print("source vertex {target:length, }")
for v in G.nodes():
    spl=single_source_shortest_path_length(G,v)
    print('%s %s' % (v,spl))
    for p in spl.values():
        pathlengths.append(p)
#取出每條路徑,計算平均值。
print('')print("average shortest path length %s" % (sum(pathlengths)/len(pathlengths)))
#路徑長度直方圖,如果路徑不存在,設為1,如果已經存在過一次,則原先基礎上加1
# histogram of path lengths
dist={}
for p in pathlengths:
    if p in dist:
        dist[p]+=1
    else:
        dist[p]=1

print('')
print("length #paths")
verts=dist.keys()
for d in sorted(verts):
    print('%s %d' % (d,dist[d]))
#內嵌函式求圖G的多個屬性
print("radius: %d" % radius(G))
print("diameter: %d" % diameter(G))
print("eccentricity: %s" % eccentricity(G))
print("center: %s" % center(G))
print("periphery: %s" % periphery(G))
print("density: %s" % density(G))