0

我在确定每个节点与起始节点的距离时遇到了一些麻烦,或者根本无法获取任何信息。我的函数没有输出,附在以下链接中。

#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

至少在我看来,我的逻辑是正确的;但是,当代码运行时,我并没有收到那么多的错误消息。

4

2 回答 2

2

你设置nearestNeighbour为一个空列表,然后你循环它for currentNode in nearestNeighbour——它什么都不做,因为列表是空的——然后你从函数中返回。

(我假设tentativeDistance是您正在调用的函数,但什么也没看到。)

于 2011-03-09T22:44:07.980 回答
1

你应该重新考虑你的算法设计。尝试查找 Dijkstra 算法的伪代码定义并在 Python 中实现它。特别是,您应该考虑程序中的控制流。

你可能想看看这个关于 Dijkstra 的 Python 实现的食谱,看看你是否能理解它。

于 2011-03-09T22:56:56.173 回答