Python - 迪杰斯特拉算法中的距离计算
我在计算每个节点离起始节点的距离时遇到了一些问题,或者说根本没有得到任何信息。
我运行的函数没有任何输出,具体代码在下面的链接里。
#Values to assign to each node
class Node:
distFromSource = infinity
previous = invalid_node
visited = False
#for each node assign default values
def populateNodeTable(network):
nodeTable = []
index = 0
f = open('network.txt', 'r')
for line in f:
node = map(int, line.split(','))
nodeTable.append(Node())
print "The previous node is " ,nodeTable[index].previous
print "The distance from source is " ,nodeTable[index].distFromSource
index +=1
nodeTable[startNode].distFromSource = 0
return nodeTable
#calculate the distance of each node from the start node
def tentativeDistance(currentNode, nodeTable):
nearestNeighbour = []
for currentNode in nearestNeighbour:
currentDistance == currentNode.distFromSource + [currentNode][nearestNeighbour] #gets current distance from source
print "The current distance"
if currentDistance != 0 & currentNode.distFromSource < Node[currentNode].distFromSource:
nodeTable[currentNode].previous = currentNode
nodeTable[currentNode].length = currentDistance
nodeTable[currentNode].visited = True
nodeTable[currentNode] +=1
nearestNeighbour.append(currentNode)
for currentNode in nearestNeighbour:
print nearestNeighbour
return nearestNeighbour
我心里觉得我的逻辑是对的,但当代码运行时,我连错误信息都没有看到。
2 个回答
1
你应该重新考虑一下你的算法设计。可以查一下Dijkstra算法的伪代码定义,然后试着用Python来实现它。特别是,你需要想想你程序中的控制流程。
你可能还想看看这个食谱,里面有Dijkstra算法的Python实现,看看你能不能理解它。
2
你把 nearestNeighbour
设置成了一个空列表,然后你用 for currentNode in nearestNeighbour
这个循环去遍历它——但是这个循环什么都不做,因为列表是空的——最后你就直接从函数里返回了。
(我猜 tentativeDistance
是你调用的那个函数,但你什么也没看到结果。)