99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀python編寫的最短路徑算法
python編寫的最短路徑算法
2017-08-20
收藏

python編寫的最短路徑算法

一心想學(xué)習(xí)算法,很少去真正靜下心來去研究,前幾天趁著周末去了解了最短路徑的資料,用python寫了一個最短路徑算法。算法是基于帶權(quán)無向圖去尋找兩個點(diǎn)之間的最短路徑,數(shù)據(jù)存儲用鄰接矩陣記錄。首先畫出一幅無向圖如下,標(biāo)出各個節(jié)點(diǎn)之間的權(quán)值。

其中對應(yīng)索引:

A ——> 0

B——> 1

C——> 2

D——>3

E——> 4

F——> 5

G——> 6

鄰接矩陣表示無向圖:

算法思想是通過Dijkstra算法結(jié)合自身想法實(shí)現(xiàn)的。大致思路是:從起始點(diǎn)開始,搜索周圍的路徑,記錄每個點(diǎn)到起始點(diǎn)的權(quán)值存到已標(biāo)記權(quán)值節(jié)點(diǎn)字典A,將起始點(diǎn)存入已遍歷列表B,然后再遍歷已標(biāo)記權(quán)值節(jié)點(diǎn)字典A,搜索節(jié)點(diǎn)周圍的路徑,如果周圍節(jié)點(diǎn)存在于表B,比較累加權(quán)值,新權(quán)值小于已有權(quán)值則更新權(quán)值和來源節(jié)點(diǎn),否則什么都不做;如果不存在與表B,則添加節(jié)點(diǎn)和權(quán)值和來源節(jié)點(diǎn)到表A,直到搜索到終點(diǎn)則結(jié)束。

這時最短路徑存在于表A中,得到終點(diǎn)的權(quán)值和來源路徑,向上遞推到起始點(diǎn),即可得到最短路徑,下面是代碼:


# -*-coding:utf-8 -*-
classDijkstraExtendPath():
  def__init__(self, node_map):
    self.node_map=node_map
    self.node_length=len(node_map)
    self.used_node_list=[]
    self.collected_node_dict={}
  def__call__(self, from_node, to_node):
    self.from_node=from_node
    self.to_node=to_node
    self._init_dijkstra()
    returnself._format_path()
  def_init_dijkstra(self):
    self.used_node_list.append(self.from_node)
    self.collected_node_dict[self.from_node]=[0,-1]
    forindex1, node1inenumerate(self.node_map[self.from_node]):
      ifnode1:
        self.collected_node_dict[index1]=[node1,self.from_node]
    self._foreach_dijkstra()
  def_foreach_dijkstra(self):
    iflen(self.used_node_list)==self.node_length-1:
      return
    forkey, valinself.collected_node_dict.items():# 遍歷已有權(quán)值節(jié)點(diǎn)
      ifkeynotinself.used_node_listandkey !=to_node:
        self.used_node_list.append(key)
      else:
        continue
      forindex1, node1inenumerate(self.node_map[key]):# 對節(jié)點(diǎn)進(jìn)行遍歷
        # 如果節(jié)點(diǎn)在權(quán)值節(jié)點(diǎn)中并且權(quán)值大于新權(quán)值
        ifnode1andindex1inself.collected_node_dictandself.collected_node_dict[index1][0] > node1+val[0]:
          self.collected_node_dict[index1][0]=node1+val[0]# 更新權(quán)值
          self.collected_node_dict[index1][1]=key
        elifnode1andindex1notinself.collected_node_dict:
          self.collected_node_dict[index1]=[node1+val[0], key]
    self._foreach_dijkstra()
  def_format_path(self):
    node_list=[]
    temp_node=self.to_node
    node_list.append((temp_node,self.collected_node_dict[temp_node][0]))
    whileself.collected_node_dict[temp_node][1] !=-1:
      temp_node=self.collected_node_dict[temp_node][1]
      node_list.append((temp_node,self.collected_node_dict[temp_node][0]))
    node_list.reverse()
    returnnode_list
defset_node_map(node_map, node, node_list):
  forx, y, valinnode_list:
    node_map[node.index(x)][node.index(y)]=node_map[node.index(y)][node.index(x)]=val
if__name__=="__main__":
  node=['A','B','C','D','E','F','G']
  node_list=[('A','F',9), ('A','B',10), ('A','G',15), ('B','F',2),
         ('G','F',3), ('G','E',12), ('G','C',10), ('C','E',1),
         ('E','D',7)]
  node_map=[[0forvalinxrange(len(node))]forvalinxrange(len(node))]
  set_node_map(node_map, node, node_list)
  # A -->; D
  from_node=node.index('A')
  to_node=node.index('D')
  dijkstrapath=DijkstraPath(node_map)
  path=dijkstrapath(from_node, to_node)
  printpath

運(yùn)行結(jié)果:

再來一例:

# -*- coding: utf-8 -*-
importitertools
importre
importmath
 
defcombination(lst): #全排序
  lists=[]
  liter=itertools.permutations(lst)
  forltsinlist(liter):
    lt=''.join(lts)
    lists.append(lt)
  returnlists
 
defcoord(lst):  #坐標(biāo)輸入
  coordinates=dict()
  printu'請輸入坐標(biāo):(格式為A:7 17)'
  p=re.compile(r"\d+")
  forcharinlst:
    str=raw_input(char+':')
    dot=p.findall(str)
    coordinates[char]=[dot[0],dot[1]]
  printcoordinates
  returncoordinates
 
defrepeat(lst): #刪除重復(fù)組合
  forilistinlst:
    forkinxrange(len(ilist)):
      st=(ilist[k:],ilist[:k])
      strs=''.join(st)
      forjlistinlst:
        if(cmp(strs,jlist)==0):
          lst.remove(jlist)
    forkinxrange(len(ilist)):
      st=(ilist[k:],ilist[:k])
      strs=''.join(st)
      forjlistinlst:
        if(cmp(strs[::-1],jlist)==0):
          lst.remove(jlist)
    lst.append(ilist)
    printlst
  returnlst
 
defcount(lst,coordinates):#計(jì)算各路徑
  way=dict()
  forstrinlst:
    str=str+str[:1]
    length=0
    foriinrange(len(str)-1):
      x=abs(float(coordinates[str[i]][0])-float(coordinates[str[i+1]][0]) )
      y=abs(float(coordinates[str[i] ][1])-float(coordinates[str[i+1] ][1]) )
      length+=math.sqrt(x**2+y**2)
    way[str[:len(str)-1]]=length
  returnway
 
if__name__=="__main__":
  printu'請輸入圖節(jié)點(diǎn):'
  rlist=list(raw_input())
  coordinates=coord(rlist)
 
  list_directive=combination(rlist)
#  print "有方向完全圖所有路徑為:",list_directive
#  for it in list_directive:
#    print it
  printu'有方向完全圖所有路徑總數(shù):',len(list_directive),"\n"
 
#無方向完全圖
  list_directive=repeat(list_directive)
  list_directive=repeat(list_directive)
#  print "無方向完全圖所有路徑為:",list_directive
  printu'無方向完全圖所有路徑為:'
  foritinlist_directive:
    printit
  printu'無方向完全圖所有路徑總數(shù):',len(list_directive)
 
  ways=count(list_directive,coordinates)
  printu'路徑排序如下:'
  fordstrinsorted(ways.iteritems(), key=lambdad:d[1], reverse=False):
    printdstr
  raw_input()

以上就是本文給大家分享的全部內(nèi)容了,希望大家能夠喜歡,能夠?qū)W習(xí)python有所幫助。


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }