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相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

(0)

相关推荐

  • Python基于回溯法子集树模板实现图的遍历功能示例

    本文实例讲述了Python基于回溯法子集树模板实现图的遍历功能.分享给大家供大家参考,具体如下: 问题 一个图: A --> B A --> C B --> C B --> D B --> E C --> A C --> D D --> C E --> F F --> C F --> D 从图中的一个节点E出发,不重复地经过所有其它节点后,回到出发节点E,称为一条路径.请找出所有可能的路径. 分析 将这个图可视化如下: 本问题涉及到图,那首

  • Python基于回溯法子集树模板解决取物搭配问题实例

    本文实例讲述了Python基于回溯法子集树模板解决取物搭配问题.分享给大家供大家参考,具体如下: 问题 有5件不同的上衣,3条不同的裤子,4顶不同的帽子,从中取出一顶帽子.一件上衣和一条裤子作为一种搭配,问有多少种不同的搭配? 分析 换个角度看,现有头.身.腿三个元素,每个元素都有各自的几种状态. 头元素有['帽1', '帽2', '帽3', '帽4']共4种状态,身元素有['衣1', '衣2', '衣3', '衣4', '衣5']共5种状态,腿元素有['裤1', '裤2', '裤3']共3种状

  • python实现dict版图遍历示例

    复制代码 代码如下: #_*_coding:utf_8_import sysimport os class Graph():    def __init__(self, V, E):        self.V = V        self.E = E        self.visited = []        self.dict = {}        self.fd = open("input.txt") def initGraph(self):        self.vi

  • Python使用回溯法子集树模板解决迷宫问题示例

    本文实例讲述了Python使用回溯法解决迷宫问题.分享给大家供大家参考,具体如下: 问题 给定一个迷宫,入口已知.问是否有路径从入口到出口,若有则输出一条这样的路径.注意移动可以从上.下.左.右.上左.上右.下左.下右八个方向进行.迷宫输入0表示可走,输入1表示墙.为方便起见,用1将迷宫围起来避免边界问题. 分析 考虑到左.右是相对的,因此修改为:北.东北.东.东南.南.西南.西.西北八个方向.在任意一格内,有8个方向可以选择,亦即8种状态可选.因此从入口格子开始,每进入一格都要遍历这8种状态.

  • Python基于回溯法子集树模板解决数字组合问题实例

    本文实例讲述了Python基于回溯法子集树模板解决数字组合问题.分享给大家供大家参考,具体如下: 问题 找出从自然数1.2.3.....n中任取r个数的所有组合. 例如,n=5,r=3的所有组合为: 1,2,3 1,2,4 1,2,5 1,3,4 1,3,5 1,4,5 2,3,4 2,3,5 2,4,5 3,4,5 分析 换个角度,r=3的所有组合,相当于元素个数为3的所有子集.因此,在遍历子集树的时候,对元素个数不为3的子树剪枝即可. 注意,这里不妨使用固定长度的解. 直接套用子集树模板.

  • Python基于回溯法子集树模板实现8皇后问题

    本文实例讲述了Python基于回溯法子集树模板实现8皇后问题.分享给大家供大家参考,具体如下: 问题 8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行.同一列或同一斜线上,问有多少种摆法. 分析 为了简化问题,考虑到8个皇后不同行,则每一行放置一个皇后,每一行的皇后可以放置于第0.1.2.....7列,我们认为每一行的皇后有8种状态.那么,我们只要套用子集树模板,从第0行开始,自上而下,对每一行的皇后,遍历它的8个状态即可. 代码: ''' 8皇后问题 '''

  • Python数据结构与算法之图结构(Graph)实例分析

    本文实例讲述了Python数据结构与算法之图结构(Graph).分享给大家供大家参考,具体如下: 图结构(Graph)--算法学中最强大的框架之一.树结构只是图的一种特殊情况. 如果我们可将自己的工作诠释成一个图问题的话,那么该问题至少已经接近解决方案了.而我们我们的问题实例可以用树结构(tree)来诠释,那么我们基本上已经拥有了一个真正有效的解决方案了. 邻接表及加权邻接字典 对于图结构的实现来说,最直观的方式之一就是使用邻接列表.基本上就是针对每个节点设置一个邻接列表.下面我们来实现一个最简

  • python数据结构之图深度优先和广度优先实例详解

    本文实例讲述了python数据结构之图深度优先和广度优先用法.分享给大家供大家参考.具体如下: 首先有一个概念:回溯 回溯法(探索与回溯法)是一种选优搜索法,按选优条件向前搜索,以达到目标.但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为"回溯点". 深度优先算法: (1)访问初始顶点v并标记顶点v已访问. (2)查找顶点v的第一个邻接顶点w. (3)若顶点v的邻接顶点w存在,则继续执行:否则回

  • Python基于回溯法子集树模板解决0-1背包问题实例

    本文实例讲述了Python基于回溯法子集树模板解决0-1背包问题.分享给大家供大家参考,具体如下: 问题 给定N个物品和一个背包.物品i的重量是Wi,其价值位Vi ,背包的容量为C.问应该如何选择装入背包的物品,使得放入背包的物品的总价值为最大? 分析 显然,放入背包的物品,是N个物品的所有子集的其中之一.N个物品中每一个物品,都有选择.不选择两种状态.因此,只需要对每一个物品的这两种状态进行遍历. 解是一个长度固定的N元0,1数组. 套用回溯法子集树模板,做起来不要太爽!!! 代码 '''0-

  • python数据结构之图的实现方法

    本文实例讲述了python数据结构之图的实现方法.分享给大家供大家参考.具体如下: 下面简要的介绍下: 比如有这么一张图: A -> B     A -> C     B -> C     B -> D     C -> D     D -> C     E -> F     F -> C 可以用字典和列表来构建 graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': [

  • python回溯法实现数组全排列输出实例分析

    本文实例讲述了python回溯法实现数组全排列输出的方法.分享给大家供大家参考.具体分析如下: 全排列解释:从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列.当m=n时所有的排列情况叫全排列. from sys import stdout #code from http://www.jb51.net/ def perm(li, start, end): if(start == end): for elem in li: stdout.wr

随机推荐