Python图算法实例分析


Posted in Python onAugust 13, 2016

本文实例讲述了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程序设计有所帮助。

Python 相关文章推荐
Python和php通信乱码问题解决方法
Apr 15 Python
python time模块用法实例详解
Sep 11 Python
Python中random模块生成随机数详解
Mar 10 Python
Python编程实现双链表,栈,队列及二叉树的方法示例
Nov 01 Python
Python cookbook(数据结构与算法)找出序列中出现次数最多的元素算法示例
Mar 15 Python
python控制nao机器人身体动作实例详解
Apr 29 Python
一篇文章了解Python中常见的序列化操作
Jun 20 Python
新手如何发布Python项目开源包过程详解
Jul 11 Python
Django项目之Elasticsearch搜索引擎的实例
Aug 21 Python
python 求定积分和不定积分示例
Nov 20 Python
python 图像的离散傅立叶变换实例
Jan 02 Python
Python中request的基本使用解决乱码问题
Apr 12 Python
Python实现八大排序算法
Aug 13 #Python
详解Python如何获取列表(List)的中位数
Aug 12 #Python
Python抓取框架 Scrapy的架构
Aug 12 #Python
判断网页编码的方法python版
Aug 12 #Python
Python利用IPython提高开发效率
Aug 10 #Python
详解python如何调用C/C++底层库与互相传值
Aug 10 #Python
浅析python中的分片与截断序列
Aug 09 #Python
You might like
使用JSON实现数据的跨域传输的php代码
2011/12/20 PHP
PHP中return 和 exit 、break和contiue 区别与用法
2012/04/09 PHP
基于PHP一些十分严重的缺陷详解
2013/06/03 PHP
PHP制作3D扇形统计图以及对图片进行缩放操作实例
2014/10/23 PHP
PHP统计当前在线用户数实例讲解
2015/10/21 PHP
解决安装WampServer时提示缺少msvcr110.dll文件的问题
2017/07/09 PHP
详细解读php的命名空间(一)
2018/02/21 PHP
jQuery EasyUI API 中文文档 - Parser 解析器
2011/09/29 Javascript
web的各种前端打印方法之jquery打印插件PrintArea实现网页打印
2013/01/09 Javascript
多个表单中如何获得这个文件上传的网址实现js代码
2013/03/25 Javascript
javascript中的原型链深入理解
2014/02/24 Javascript
javascript判断office版本示例
2014/04/11 Javascript
用NODE.JS中的流编写工具是要注意的事项
2016/03/01 Javascript
jQuery实现的纵向下拉菜单实例详解【附demo源码下载】
2016/07/09 Javascript
js 弹出对话框(遮罩)透明,可拖动的简单实例
2016/07/11 Javascript
js 弹出虚拟键盘修改密码的简单实例
2016/10/10 Javascript
微信小程序 progress组件详解及实例代码
2016/10/25 Javascript
webpack配置proxyTable时pathRewrite无效的解决方法
2018/12/13 Javascript
vue项目中使用scss的方法步骤
2019/05/16 Javascript
浅析vue-router中params和query的区别
2019/12/24 Javascript
使用python检测手机QQ在线状态的脚本代码
2013/02/10 Python
在Python中封装GObject模块进行图形化程序编程的教程
2015/04/14 Python
Python使用urllib2模块实现断点续传下载的方法
2015/06/17 Python
python中requests小技巧
2017/05/10 Python
python基于pdfminer库提取pdf文字代码实例
2019/08/15 Python
python 正则表达式参数替换实例详解
2020/01/17 Python
如何利用python之wxpy模块玩转微信
2020/08/17 Python
Python利用Pillow(PIL)库实现验证码图片的全过程
2020/10/04 Python
详解Django ORM引发的数据库N+1性能问题
2020/10/12 Python
phpquery中文手册
2021/03/18 PHP
广告设计专业自荐信范文
2013/11/14 职场文书
中餐厅经理岗位职责
2014/04/11 职场文书
2016自主招生教师推荐信范文
2015/03/23 职场文书
人生感悟经典句子
2019/08/20 职场文书
CSS3点击按钮圆形进度打钩效果的实现代码
2021/03/30 HTML / CSS
深入浅析Redis 集群伸缩原理
2021/05/15 Redis