Python圖算法實(shí)例分析
本文實(shí)例講述了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) <= 1: return 0 links = 0 for j in neighbors: for k in neighbors: if j in self.Link[k]: links += 0.5 return 2.0*links/(len(neighbors)*(len(neighbors)-1)) def AverageClusteringCoefficient(self): total = 0.0 for node in self.Link.keys(): total += self.LocalClusteringCoefficient(node) return total/len(self.Link.keys()) def DeepFirstSearch(self,start): visitedNodes = [] todoList = [start] while todoList: visit = todoList.pop(0) if visit not in visitedNodes: visitedNodes.append(visit) todoList = self.Link[visit].keys() + todoList return visitedNodes def BreadthFirstSearch(self,start): visitedNodes = [] todoList = [start] while todoList: visit = todoList.pop(0) if visit not in visitedNodes: visitedNodes.append(visit) todoList = todoList + self.Link[visit].keys() return visitedNodes def ListAllComponent(self): allComponent = [] visited = {} for node in self.Link.iterkeys(): if node not in visited: oneComponent = self.MakeComponent(node,visited) allComponent.append(oneComponent) return allComponent def CheckConnection(self,node1,node2): return True if node2 in self.MakeComponent(node1,{}) else False def MakeComponent(self,node,visited): visited[node] = True component = [node] for neighbor in self.Link[node]: if neighbor not in visited: component += self.MakeComponent(neighbor,visited) return component def MinimumSpanningTree_Kruskal(self,start): graphEdges = [line.strip('\n').split(self.Separator) for line in open(self.FileName,'r')] nodeSet = {} for idx,node in enumerate(self.MakeComponent(start,{})): nodeSet[node] = idx edgeNumber = 0; totalEdgeNumber = len(nodeSet)-1 for oneEdge in sorted(graphEdges,key=lambda x:int(x[2]),reverse=False): if edgeNumber == totalEdgeNumber: break nodeA,nodeB,cost = oneEdge if nodeA in nodeSet and nodeSet[nodeA] != nodeSet[nodeB]: nodeBSet = nodeSet[nodeB] for node in nodeSet.keys(): if nodeSet[node] == nodeBSet: nodeSet[node] = nodeSet[nodeA] print nodeA,nodeB,cost edgeNumber += 1 def MinimumSpanningTree_Prim(self,start): expandNode = set(self.MakeComponent(start,{})) distFromTreeSoFar = {}.fromkeys(expandNode,sys.maxint); distFromTreeSoFar[start] = 0 linkToNode = {}.fromkeys(expandNode,'');linkToNode[start] = start while expandNode: # Find the closest dist node closestNode = ''; shortestdistance = sys.maxint; for node,dist in distFromTreeSoFar.iteritems(): if node in expandNode and dist < shortestdistance: closestNode,shortestdistance = node,dist expandNode.remove(closestNode) print linkToNode[closestNode],closestNode,shortestdistance for neighbor in self.Link[closestNode].iterkeys(): recomputedist = self.Link[closestNode][neighbor] if recomputedist < distFromTreeSoFar[neighbor]: distFromTreeSoFar[neighbor] = recomputedist linkToNode[neighbor] = closestNode def ShortestPathOne2One(self,start,end): pathFromStart = {} pathFromStart[start] = [start] todoList = [start] while todoList: current = todoList.pop(0) for neighbor in self.Link[current]: if neighbor not in pathFromStart: pathFromStart[neighbor] = pathFromStart[current] + [neighbor] if neighbor == end: return pathFromStart[end] todoList.append(neighbor) return [] def Centrality(self,node): path2All = self.ShortestPathOne2All(node) # The average of the distances of all the reachable nodes return float(sum([len(path)-1 for path in path2All.itervalues()]))/len(path2All) def SingleSourceShortestPath_Dijkstra(self,start): expandNode = set(self.MakeComponent(start,{})) distFromSourceSoFar = {}.fromkeys(expandNode,sys.maxint); distFromSourceSoFar[start] = 0 while expandNode: # Find the closest dist node closestNode = ''; shortestdistance = sys.maxint; for node,dist in distFromSourceSoFar.iteritems(): if node in expandNode and dist < shortestdistance: closestNode,shortestdistance = node,dist expandNode.remove(closestNode) for neighbor in self.Link[closestNode].iterkeys(): recomputedist = distFromSourceSoFar[closestNode] + self.Link[closestNode][neighbor] if recomputedist < distFromSourceSoFar[neighbor]: distFromSourceSoFar[neighbor] = recomputedist for node in distFromSourceSoFar: print start,node,distFromSourceSoFar[node] def AllpairsShortestPaths_MatrixMultiplication(self,start): nodeIdx = {}; idxNode = {}; for idx,node in enumerate(self.MakeComponent(start,{})): nodeIdx[node] = idx; idxNode[idx] = node matrixSize = len(nodeIdx) MaxInt = 1000 nodeMatrix = array([[MaxInt]*matrixSize]*matrixSize) for node in nodeIdx.iterkeys(): nodeMatrix[nodeIdx[node]][nodeIdx[node]] = 0 for line in open(self.FileName,'r'): nodeA,nodeB,cost = line.strip('\n').split(self.Separator) if nodeA in nodeIdx: nodeMatrix[nodeIdx[nodeA]][nodeIdx[nodeB]] = int(cost) nodeMatrix[nodeIdx[nodeB]][nodeIdx[nodeA]] = int(cost) result = array([[0]*matrixSize]*matrixSize) for i in xrange(matrixSize): for j in xrange(matrixSize): result[i][j] = nodeMatrix[i][j] for itertime in xrange(2,matrixSize): for i in xrange(matrixSize): for j in xrange(matrixSize): if i==j: result[i][j] = 0 continue result[i][j] = MaxInt for k in xrange(matrixSize): result[i][j] = min(result[i][j],result[i][k]+nodeMatrix[k][j]) for i in xrange(matrixSize): for j in xrange(matrixSize): if result[i][j] != MaxInt: print idxNode[i],idxNode[j],result[i][j] def ShortestPathOne2All(self,start): pathFromStart = {} pathFromStart[start] = [start] todoList = [start] while todoList: current = todoList.pop(0) for neighbor in self.Link[current]: if neighbor not in pathFromStart: pathFromStart[neighbor] = pathFromStart[current] + [neighbor] todoList.append(neighbor) return pathFromStart def NDegreeNode(self,start,n): pathFromStart = {} pathFromStart[start] = [start] pathLenFromStart = {} pathLenFromStart[start] = 0 todoList = [start] while todoList: current = todoList.pop(0) for neighbor in self.Link[current]: if neighbor not in pathFromStart: pathFromStart[neighbor] = pathFromStart[current] + [neighbor] pathLenFromStart[neighbor] = pathLenFromStart[current] + 1 if pathLenFromStart[neighbor] <= n+1: todoList.append(neighbor) for node in pathFromStart.keys(): if len(pathFromStart[node]) != n+1: del pathFromStart[node] return pathFromStart def Draw(self): G = networkx.Graph() nodes = self.Link.keys() edges = [(node,neighbor) for node in nodes for neighbor in self.Link[node]] G.add_edges_from(edges) networkx.draw(G) pyplot.show() if __name__=='__main__': separator = '\t' filename = 'C:\\Users\\Administrator\\Desktop\\graphdata.txt' resultfilename = 'C:\\Users\\Administrator\\Desktop\\result.txt' myGraph = Graph() myGraph.MakeLink(filename,separator) print 'LocalClusteringCoefficient',myGraph.LocalClusteringCoefficient('a') print 'AverageClusteringCoefficient',myGraph.AverageClusteringCoefficient() print 'DeepFirstSearch',myGraph.DeepFirstSearch('a') print 'BreadthFirstSearch',myGraph.BreadthFirstSearch('a') print 'ShortestPathOne2One',myGraph.ShortestPathOne2One('a','d') print 'ShortestPathOne2All',myGraph.ShortestPathOne2All('a') print 'NDegreeNode',myGraph.NDegreeNode('a',3).keys() print 'ListAllComponent',myGraph.ListAllComponent() print 'CheckConnection',myGraph.CheckConnection('a','f') print 'Centrality',myGraph.Centrality('c') myGraph.MinimumSpanningTree_Kruskal('a') myGraph.AllpairsShortestPaths_MatrixMultiplication('a') myGraph.MinimumSpanningTree_Prim('a') myGraph.SingleSourceShortestPath_Dijkstra('a') # myGraph.Draw()
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專(zhuān)題:《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門(mén)與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- python實(shí)現(xiàn)dict版圖遍歷示例
- Python數(shù)據(jù)結(jié)構(gòu)與算法之圖結(jié)構(gòu)(Graph)實(shí)例分析
- python數(shù)據(jù)結(jié)構(gòu)之圖的實(shí)現(xiàn)方法
- python數(shù)據(jù)結(jié)構(gòu)之圖深度優(yōu)先和廣度優(yōu)先實(shí)例詳解
- Python基于回溯法子集樹(shù)模板解決取物搭配問(wèn)題實(shí)例
- Python基于回溯法子集樹(shù)模板解決數(shù)字組合問(wèn)題實(shí)例
- Python基于回溯法子集樹(shù)模板解決0-1背包問(wèn)題實(shí)例
- Python使用回溯法子集樹(shù)模板解決迷宮問(wèn)題示例
- Python基于回溯法子集樹(shù)模板實(shí)現(xiàn)8皇后問(wèn)題
- python回溯法實(shí)現(xiàn)數(shù)組全排列輸出實(shí)例分析
- Python基于回溯法子集樹(shù)模板實(shí)現(xiàn)圖的遍歷功能示例
相關(guān)文章
解決新django中的path不能使用正則表達(dá)式的問(wèn)題
今天小編就為大家分享一篇解決新django中的path不能使用正則表達(dá)式的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12Python根據(jù)字符串調(diào)用函數(shù)過(guò)程解析
這篇文章主要介紹了Python根據(jù)字符串調(diào)用函數(shù)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11tensorflow學(xué)習(xí)教程之文本分類(lèi)詳析
初學(xué)tensorflow,借鑒了很多別人的經(jīng)驗(yàn),參考博客對(duì)評(píng)論分類(lèi)(感謝博主的一系列好文),本人也嘗試著實(shí)現(xiàn)了對(duì)文本數(shù)據(jù)的分類(lèi),下面這篇文章主要給大家介紹了關(guān)于tensorflow學(xué)習(xí)教程之文本分類(lèi)的相關(guān)資料,需要的朋友可以參考下2018-08-08tensorflow中tf.reduce_mean函數(shù)的使用
這篇文章主要介紹了tensorflow中tf.reduce_mean函數(shù)的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04實(shí)現(xiàn)Python圖形界面框架TkInter寫(xiě)GUI界面應(yīng)用簡(jiǎn)介過(guò)程操作
TkInter是Python用于開(kāi)發(fā)GUI界面的標(biāo)準(zhǔn)庫(kù),如果你想快速開(kāi)發(fā)一個(gè)帶有GUI界面的小工具(笑小程序),且又能同時(shí)在Linux、Windows、Mac上使用,TkInter天生支持跨平臺(tái),天生具備穩(wěn)定性,我認(rèn)為它能滿足內(nèi)部工具的簡(jiǎn)單需求2021-09-09學(xué)習(xí)python需要有編程基礎(chǔ)嗎
在本篇文章里小編給大家分享的是一篇關(guān)于學(xué)習(xí)python有哪些必要條件,需要的朋友們可以學(xué)習(xí)下。2020-06-06Python分支語(yǔ)句與循環(huán)語(yǔ)句應(yīng)用實(shí)例分析
這篇文章主要介紹了Python分支語(yǔ)句與循環(huán)語(yǔ)句應(yīng)用,結(jié)合具體實(shí)例形式詳細(xì)分析了Python分支語(yǔ)句與循環(huán)語(yǔ)句各種常見(jiàn)應(yīng)用操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-05-05