最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python圖算法實例分析

 更新時間:2016年08月13日 10:57:14   作者:intergret  
這篇文章主要介紹了Python圖算法,結合實例形式詳細分析了Python數(shù)據(jù)結構與算法中的圖算法實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了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相關內(nèi)容可查看本站專題:《Python正則表達式用法總結》、《Python數(shù)據(jù)結構與算法教程》、《Python Socket編程技巧總結》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設計有所幫助。

相關文章

  • 利用Jmeter實現(xiàn)在請求param和body里面加入隨機參數(shù)

    利用Jmeter實現(xiàn)在請求param和body里面加入隨機參數(shù)

    本文介紹了如何使用jemeter實現(xiàn)新增接口壓力測試中的隨機參數(shù)生成,首先,使用函數(shù)助手對話框生成隨機數(shù),然后將生成的隨機數(shù)作為參數(shù)放入請求中,無論請求格式是json、xml還是text等,如果param和body同時存在并需要隨機生成參數(shù),可以把參數(shù)寫入到請求地址中
    2024-10-10
  • python將unicode和str互相轉化的實現(xiàn)

    python將unicode和str互相轉化的實現(xiàn)

    這篇文章主要介紹了python將unicode和str互相轉化的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • 一文詳解Python中的Map,Filter和Reduce函數(shù)

    一文詳解Python中的Map,Filter和Reduce函數(shù)

    這篇文章主要介紹了一文詳解Python中的Map,Filter和Reduce函數(shù),本文重點介紹Python中的三個特殊函數(shù)Map,Filter和Reduce,以及如何使用它們進行代碼編程
    2022-08-08
  • 基于高德地圖API在Python中實現(xiàn)地圖功能的方法示例詳解

    基于高德地圖API在Python中實現(xiàn)地圖功能的方法示例詳解

    本文介紹在高德開放平臺中,申請、獲取地圖API的Key的方法,同時通過簡單的Python代碼,調(diào)取API信息,對所得Key的可用性加以驗證,感興趣的朋友一起看看吧
    2025-01-01
  • 詳解Python腳本如何消費多個Kafka?topic

    詳解Python腳本如何消費多個Kafka?topic

    kafka-python庫是一個流行的Kafka客戶端庫,本文主要為大家詳細介紹了如何通過這個庫創(chuàng)建一個Kafka消費者,并同時消費多個Kafka?topic,需要的可以了解下
    2024-11-11
  • Python控制鍵盤鼠標pynput的詳細用法

    Python控制鍵盤鼠標pynput的詳細用法

    這篇文章主要介紹了Python控制鍵盤鼠標pynput的詳細用法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01
  • python實現(xiàn)對指定輸入的字符串逆序輸出的6種方法

    python實現(xiàn)對指定輸入的字符串逆序輸出的6種方法

    這篇文章主要介紹了python實現(xiàn)對指定輸入的字符串逆序輸出的6種方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • 詳解超星腳本出現(xiàn)亂碼問題的解決方法(Python)

    詳解超星腳本出現(xiàn)亂碼問題的解決方法(Python)

    超星助手是一款為孩子們提供學習的軟件,支持用戶們后臺運行多開等,還可以簽到,查題等多功能,下面這篇文章主要給大家介紹了關于超星腳本出現(xiàn)亂碼問題的解決方法,需要的朋友可以參考下
    2022-05-05
  • Flask框架Flask-Login用法分析

    Flask框架Flask-Login用法分析

    這篇文章主要介紹了Flask框架Flask-Login用法,結合實例形式分析了Flask-Login插件進行登錄驗證的相關操作技巧與注意事項,需要的朋友可以參考下
    2018-07-07
  • Python實現(xiàn)隨機森林算法的示例代碼

    Python實現(xiàn)隨機森林算法的示例代碼

    隨機森林的英文是 Random Forest,英文簡寫是 RF,也是常用的人工智能算法,本文為大家介紹了Python實現(xiàn)隨機森林算法的示例代碼,希望對大家有所幫助
    2023-06-06

最新評論

霍林郭勒市| 兖州市| 温州市| 柳林县| 交口县| 潍坊市| 永川市| 南华县| 岳阳市| 福安市| 北川| 凤翔县| 四平市| 五台县| 黎川县| 马龙县| 信宜市| 长兴县| 藁城市| 上思县| 汉寿县| 兴隆县| 中江县| 乌拉特后旗| 绥芬河市| 赤城县| 堆龙德庆县| 吐鲁番市| 灵璧县| 麻阳| 富锦市| 浦城县| 景洪市| 织金县| 钟山县| 延长县| 内黄县| 启东市| 石柱| 台东县| 阳春市|