这篇文章主要介绍了python图算法,结合实例形式详细分析了python数据结构与算法中的图算法实现技巧,需要的朋友可以参考下
本文实例讲述了python图算法。分享给大家供大家参考,具体如下:
#encoding=utf-8
import networkx,heapq,sys
from matplotlib import pyplot
from collections import defaultdict,ordereddict
from numpy import array
# data in graphdata.txt:
# a b 4
# a h 8
# b c 8
# b h 11
# h i 7
# h g 1
# g i 6
# g f 2
# c f 4
# c i 2
# c d 7
# d f 14
# d e 9
# f e 10
def edge(): return defaultdict(edge)
class graph:
def __init__(self):
self.link = edge()
self.filename = ”
self.separator = ”
def makelink(self,filename,separator):
self.filename = filename
self.separator = separator
graphfile = open(filename,’r’)
for line in graphfile:
items = line.split(separator)
self.link[items[0]][items[1]] = int(items[2])
self.link[items[1]][items[0]] = int(items[2])
graphfile.close()
def localclusteringcoefficient(self,node):
neighbors = self.link[node]
if len(neighbors)