本文实例讲述了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相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
京东创始人刘强东和其妻子章泽天最近成为了互联网舆论关注的焦点。有关他们“移民美国”和在美国购买豪宅的传言在互联网上广泛传播。然而,京东官方通过微博发言人发布的消息澄清了这些传言,称这些言论纯属虚假信息和蓄意捏造。
日前,据博主“@超能数码君老周”爆料,国内三大运营商中国移动、中国电信和中国联通预计将集体采购百万台规模的华为Mate60系列手机。
据报道,荷兰半导体设备公司ASML正看到美国对华遏制政策的负面影响。阿斯麦(ASML)CEO彼得·温宁克在一档电视节目中分享了他对中国大陆问题以及该公司面临的出口管制和保护主义的看法。彼得曾在多个场合表达了他对出口管制以及中荷经济关系的担忧。
今年早些时候,抖音悄然上线了一款名为“青桃”的 App,Slogan 为“看见你的热爱”,根据应用介绍可知,“青桃”是一个属于年轻人的兴趣知识视频平台,由抖音官方出品的中长视频关联版本,整体风格有些类似B站。
日前,威马汽车首席数据官梅松林转发了一份“世界各国地区拥车率排行榜”,同时,他发文表示:中国汽车普及率低于非洲国家尼日利亚,每百户家庭仅17户有车。意大利世界排名第一,每十户中九户有车。
近日,一项新的研究发现,维生素 C 和 E 等抗氧化剂会激活一种机制,刺激癌症肿瘤中新血管的生长,帮助它们生长和扩散。
据媒体援引消息人士报道,苹果公司正在测试使用3D打印技术来生产其智能手表的钢质底盘。消息传出后,3D系统一度大涨超10%,不过截至周三收盘,该股涨幅回落至2%以内。
9月2日,坐拥千万粉丝的网红主播“秀才”账号被封禁,在社交媒体平台上引发热议。平台相关负责人表示,“秀才”账号违反平台相关规定,已封禁。据知情人士透露,秀才近期被举报存在违法行为,这可能是他被封禁的部分原因。据悉,“秀才”年龄39岁,是安徽省亳州市蒙城县人,抖音网红,粉丝数量超1200万。他曾被称为“中老年...
9月3日消息,亚马逊的一些股东,包括持有该公司股票的一家养老基金,日前对亚马逊、其创始人贝索斯和其董事会提起诉讼,指控他们在为 Project Kuiper 卫星星座项目购买发射服务时“违反了信义义务”。
据消息,为推广自家应用,苹果现推出了一个名为“Apps by Apple”的网站,展示了苹果为旗下产品(如 iPhone、iPad、Apple Watch、Mac 和 Apple TV)开发的各种应用程序。
特斯拉本周在美国大幅下调Model S和X售价,引发了该公司一些最坚定支持者的不满。知名特斯拉多头、未来基金(Future Fund)管理合伙人加里·布莱克发帖称,降价是一种“短期麻醉剂”,会让潜在客户等待进一步降价。
据外媒9月2日报道,荷兰半导体设备制造商阿斯麦称,尽管荷兰政府颁布的半导体设备出口管制新规9月正式生效,但该公司已获得在2023年底以前向中国运送受限制芯片制造机器的许可。
近日,根据美国证券交易委员会的文件显示,苹果卫星服务提供商 Globalstar 近期向马斯克旗下的 SpaceX 支付 6400 万美元(约 4.65 亿元人民币)。用于在 2023-2025 年期间,发射卫星,进一步扩展苹果 iPhone 系列的 SOS 卫星服务。
据报道,马斯克旗下社交平台𝕏(推特)日前调整了隐私政策,允许 𝕏 使用用户发布的信息来训练其人工智能(AI)模型。新的隐私政策将于 9 月 29 日生效。新政策规定,𝕏可能会使用所收集到的平台信息和公开可用的信息,来帮助训练 𝕏 的机器学习或人工智能模型。
9月2日,荣耀CEO赵明在采访中谈及华为手机回归时表示,替老同事们高兴,觉得手机行业,由于华为的回归,让竞争充满了更多的可能性和更多的魅力,对行业来说也是件好事。
《自然》30日发表的一篇论文报道了一个名为Swift的人工智能(AI)系统,该系统驾驶无人机的能力可在真实世界中一对一冠军赛里战胜人类对手。
近日,非营利组织纽约真菌学会(NYMS)发出警告,表示亚马逊为代表的电商平台上,充斥着各种AI生成的蘑菇觅食科普书籍,其中存在诸多错误。
社交媒体平台𝕏(原推特)新隐私政策提到:“在您同意的情况下,我们可能出于安全、安保和身份识别目的收集和使用您的生物识别信息。”
2023年德国柏林消费电子展上,各大企业都带来了最新的理念和产品,而高端化、本土化的中国产品正在不断吸引欧洲等国际市场的目光。
罗永浩日前在直播中吐槽苹果即将推出的 iPhone 新品,具体内容为:“以我对我‘子公司’的了解,我认为 iPhone 15 跟 iPhone 14 不会有什么区别的,除了序(列)号变了,这个‘不要脸’的东西,这个‘臭厨子’。