确定Dijkstra中的最近邻

时间:2011-03-13 01:58:28

标签: python dijkstra

好的,我已经改变了一些代码,但是我对于应该将哪些变量名称传递给myNeighBour函数感到困惑。这两个功能可以正常工作:

infinity = 1000000
invalid_node = -1
startNode = 0

#Values to assign to each node
class Node:
     def __init__(self):
       self.distFromSource = infinity
       self.previous = invalid_node
       self.visited = False

#read in all network nodes
#node = the distance values between nodes
def network():
    f = open ('network.txt', 'r')
    theNetwork = [[int(networkNode) for networkNode in line.split(',')] for line in f.readlines()]
    #theNetwork = [[int(node) for node in line.split(',')] for line in f.readlines()]
    #print theNetwork

    return theNetwork

#for each node assign default values
#populate table with default values
def populateNodeTable(): 
    nodeTable = []
    index = 0
    f = open('network.txt', 'r')
    for line in f: 
      networkNode = map(int, line.split(',')) 
      nodeTable.append(Node())

      #print "The previous node is " ,nodeTable[index].previous 
      #print "The distance from source is " ,nodeTable[index].distFromSource
      #print networkNode
      index +=1
    nodeTable[startNode].distFromSource = 0 

    return nodeTable

所以,一切都很好。但是,我的下一个功能是给我一个错误,尽管我在括号中更改了变量名,但我无法解决问题。这是下一个功能代码和错误消息:

def nearestNeighbour(nodeTable, theNetwork):
     listOfNeighbours = []
     nodeIndex = 0
     for networkNode in nodeTable[currentNode]:
          if networkNode != 0 and networkNode.visited == False: 
             listOfNeighbours.append(nearestNode)
          nodeIndex +=1
     print listOfNeighbours
##     #print node.distFromSource, node.previous, node.visited
##
     return listOfNeighbours

for networkNode in nodeTable[currentNode]:
TypeError: iteration over non-sequence

1 个答案:

答案 0 :(得分:1)

我认为您需要nodeTable[node],而不是node[nodeTable],与theNetwork[node]类似。