Python graph algorithm

Source: Internet
Author: User
This article mainly introduced the Python graph algorithm, combined with the example form detailed analysis Python data structure and algorithm in the graph algorithm realization skill, needs the friend can refer to the next

The example in this paper describes the Python graph algorithm. Share to everyone for your reference, as follows:

#encoding =utf-8import networkx,heapq,sysfrom matplotlib Import pyplotfrom collections Import Defaultdict,  Ordereddictfrom numpy import array# Data in graphdata.txt:# a b 4# a h 8# b c 8# B h 11# h i 7# h G # G I 6# G f    C F 4# c i c D 7# D f 14# d e 9# f E 10def 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 = s Elf.  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 to 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 (V isit) 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.st RIP (' \ 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 Edgenu Mber = = Totaledgenumber:break Nodea,nodeb,cost = Oneedge if NodeA in NodeSet and Nodeset[nodea]! = Nodeset[node            B]: 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:clos Estnode,shortestdistance = Node,dist expandnode.remove (closestnode) Print Linktonode[closestnode],closestnode,sh Ortestdistance 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] + [neigh Bor] if neighbor = = End:return Pathfromstart[end] Todolist.append (neighbor) return [] de F centrality (Self,node): Path2all = self. Shortestpathone2all (node) # The average of the distances of all the reachable nodes return float (sum ([Len Path)-1 fo R path in Path2all.itervalues ()])/len (path2all) def Singlesourceshortestpath_dijkstra (self,start): Expandnode = set (s Elf. 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[neigh Bor] = recomputedist for node in Distfromsourcesofar:print Start,node,distfromsourcesofar[node] def allpairsshor Testpaths_matrixmultiplication (self,start): Nodeidx = {};     Idxnode = {}; For Idx,node in enumerate (self. Makecomponent (start,{})): Nodeidx[node] = idx;    IDXNODE[IDX] = node matrixsize = Len (nodeidx) MaxInt = 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 Xrang E (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): path      Fromstart = {} 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 T odolist:current = Todolist.pop (0) for neighbor in self. Link[current]: If neighbor not in pathfromstart:pathfromstart[neighbor] = pathfromstart[current] + [neigh             Bor] 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 ' fil ename = ' 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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.