我遇到了我的代码问题,我无法计算从起始节点到节点的距离。我有以下形式的文本文件: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