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黑魔法之参数传递
Feb 12 Python
python3.5 + PyQt5 +Eric6 实现的一个计算器代码
Mar 11 Python
python让列表倒序输出的实例
Jun 25 Python
Python用61行代码实现图片像素化的示例代码
Dec 10 Python
使用Python Pandas处理亿级数据的方法
Jun 24 Python
python取余运算符知识点详解
Jun 27 Python
使用Python脚本zabbix自定义key监控oracle连接状态
Aug 28 Python
python多进程(加入进程池)操作常见案例
Oct 21 Python
用什么库写 Python 命令行程序(示例代码详解)
Feb 20 Python
jupyter note 实现将数据保存为word
Apr 14 Python
pycharm全局搜索的具体步骤
Jul 28 Python
PyCharm2020.1.1与Python3.7.7的安装教程图文详解
Aug 07 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
生成sessionid和随机密码的例子
2006/10/09 PHP
使用PHP 5.0创建图形的巧妙方法
2010/10/12 PHP
Yii2组件之多图上传插件FileInput的详细使用教程
2016/06/20 PHP
jQuery源码分析之Event事件分析
2010/06/07 Javascript
JS无限极树形菜单,json格式、数组格式通用示例
2013/07/30 Javascript
jQuery的观察者模式详解
2014/12/22 Javascript
Javascript简单改变表单元素背景的方法
2015/07/15 Javascript
轻松学习jQuery插件EasyUI EasyUI创建RSS Feed阅读器
2015/11/30 Javascript
angular+webpack2实战例子
2017/05/23 Javascript
使用vue-resource进行数据交互的实例
2017/09/02 Javascript
vue2组件之select2调用的示例代码
2017/10/12 Javascript
javascript浏览器用户代理检测脚本实现方法
2017/10/27 Javascript
微信小程序学习笔记之表单提交与PHP后台数据交互处理图文详解
2019/03/28 Javascript
react 中父组件与子组件双向绑定问题
2019/05/20 Javascript
js实现鼠标拖拽div左右滑动
2020/01/15 Javascript
[01:46]TI4西雅图DOTA2前线报道 中国选手抱团调时差
2014/07/08 DOTA
python 装饰器功能以及函数参数使用介绍
2012/01/27 Python
Python实现抓取城市的PM2.5浓度和排名
2015/03/19 Python
Python中自定义函数的教程
2015/04/27 Python
用vue.js组件模拟v-model指令实例方法
2019/07/05 Python
Keras实现DenseNet结构操作
2020/07/06 Python
使用python实现下载我们想听的歌曲,速度超快
2020/07/09 Python
解决Python中导入自己写的类,被划红线,但不影响执行的问题
2020/07/13 Python
CSS3教程:边框属性border的极致应用
2009/04/02 HTML / CSS
英国HYPE双肩包官网:英国本土时尚潮牌
2018/09/26 全球购物
June Jacobs尊积帕官网:知名的spa水疗护肤品牌
2019/03/21 全球购物
土木工程师职业规划范文
2014/03/07 职场文书
公司请假条格式
2014/04/11 职场文书
乡镇干部党的群众路线教育实践活动个人对照检查材料
2014/09/24 职场文书
党的群众路线教育实践活动个人对照检查材料(教师)
2014/11/04 职场文书
先进单位事迹材料
2014/12/25 职场文书
2015年实习生工作总结报告
2015/04/28 职场文书
2015年税务稽查工作总结
2015/05/26 职场文书
2015年员工试用期工作总结
2015/05/28 职场文书
mongodb的安装和开机自启动详细讲解
2021/08/02 MongoDB
Golang并发操作中常见的读写锁详析
2021/08/30 Golang