我遇到了我的代碼問題,我無法計算從起始節點到節點的距離。我有以下形式的文本文件:Python - Dijsktra的算法距離問題
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8, 9
這表示圖中的節點距離。不幸的是,儘管嘗試了幾種不同的方法,但我仍然不斷地提出各種錯誤消息,這裏是我的代碼。
infinity = 1000000
invalid_node = -1
startNode = 0
class Node:
distFromSource = infinity
previous = invalid_node
visited = False
def populateNodeTable():
nodeTable = []
index =0
f = open('route.txt', 'r')
for line in f:
node = map(int, line.split(','))
nodeTable.append(Node())
print nodeTable[index].previous
print nodeTable[index].distFromSource
index +=1
nodeTable[startNode].distFromSource = 0
return nodeTable
def tentativeDistance(currentNode, nodeTable):
nearestNeighbour = []
for currentNode in nodeTable:
# if Node[currentNode].distFromSource + currentDistance = startNode + currentNode
# currentDistance = currentNode.distFromSource + nodeTable.currentNode
currentNode.previous = currentNode
currentNode.length = currentDistance
currentNode.visited = True
currentNode +=1
nearestNeighbour.append(currentNode)
print nearestNeighbour
return nearestNeighbour
def shortestPath (nearestNeighbour)
shortestPath = []
f = open ('spf.txt', 'r')
f.close()
currentNode = startNode
if __name__ == "__main__":
populateNodeTable()
tentativeDistance(currentNode,populateNodeTable())
在我的tentativeDistance函數中以'#'開頭的行是給我帶來麻煩的部分。我已經在網上看了一些其他的實現,雖然他們讓我困惑
代碼的格式不' t看起來沒錯。這使得難以遵循。你可以嘗試修復縮進嗎? – dappawit 2011-03-08 20:40:39
縮進被打破。你可能想要檢查一下,在粘貼之前你沒有混合製表符和空格 – 2011-03-08 20:40:42
它已被編輯,適用於我,除了給我提供問題的函數外 – user612041 2011-03-08 20:50:12