这篇文章主要介绍了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) <= 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()
更多Python图算法相关文章请关注PHP中文网!

기사는 구문 모호성으로 인해 파이썬에서 튜플 이해의 불가능성에 대해 논의합니다. 튜플을 효율적으로 생성하기 위해 튜플 ()을 사용하는 것과 같은 대안이 제안됩니다. (159 자)

이 기사는 파이썬의 모듈과 패키지, 차이점 및 사용법을 설명합니다. 모듈은 단일 파일이고 패키지는 __init__.py 파일이있는 디렉토리이며 관련 모듈을 계층 적으로 구성합니다.

기사는 Python의 Docstrings, 사용법 및 혜택에 대해 설명합니다. 주요 이슈 : 코드 문서 및 접근성에 대한 문서의 중요성.

기사는 Lambda 기능, 일반 기능과의 차이 및 프로그래밍 시나리오에서의 유틸리티에 대해 설명합니다. 모든 언어가 그들을 지원하는 것은 아닙니다.

기사는 파괴, 계속 및 Python을 통과시켜 루프 실행 및 프로그램 흐름을 제어하는 역할을 설명합니다.

이 기사는 기능 및 클래스와 같은 코드 구조에서 자리 표시 자로 사용되는 NULL 작업 인 Python의 'Pass'명령문에 대해 설명하여 구문 오류없이 향후 구현을 허용합니다.

기사는 파이썬의 인수와 같은 기능을 전달하는 것에 대해 논의하며, 모듈성과 같은 이점 및 분류 및 장식기와 같은 사용 사례를 강조합니다.

기사는 Python의 / 및 // 연산자에 대해 논의합니다 : / True Division, // for floor division. 주요 이슈는 차이점과 사용 사례를 이해하는 것입니다. 문자 수 : 158


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기
