0

ダイクストラアルゴリズムコードで理解できないエラーが発生しました-エラーメッセージは次のとおりです。

Traceback (most recent call last):
  File "C:\Documents and Settings\Harvey\Desktop\algorithm.py", line 52, in <module>
    tentativeDistance(currentNode,populateNodeTable())
  File "C:\Documents and Settings\Harvey\Desktop\algorithm.py", line 29, in tentativeDistance
    currentDistance = nodeTable[currentNode].distFromSource + network[currentNode][nearestNeighbour] #gets current distance from source
TypeError: object cannot be interpreted as an index

これが私のコードです:

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 
    #currentNode = nodeTable[startNode] 

    return nodeTable

def tentativeDistance(currentNode, nodeTable):
    nearestNeighbour = []
    #j = nodeTable[startNode]
    for currentNode in nodeTable:
      currentDistance = nodeTable[currentNode].distFromSource + network[currentNode][nearestNeighbour] #gets current distance from source
      if currentDistance != 0 & NodeTable[currentNode].distFromSource < Node[currentNode].distFromSource:
         nodeTable[currentNode].previous = currentNode
         nodeTable[currentNode].length = currentDistance
         nodeTable[currentNode].visited = True
         nodeTable[currentNode] +=1
         nearestNeighbour.append(currentNode)
      print nearestNeighbour

    return nearestNeighbour

currentNode = startNode

if __name__ == "__main__":
    populateNodeTable()
    tentativeDistance(currentNode,populateNodeTable())

私の最初の関数は正しく実行され、ソリューションをオンラインで検索しても効果がないことが証明されていますが、私のロジックは2番目の関数に対して正しいです

4

1 に答える 1

3

Pythonでループが機能する方法を考えると、for書く必要はありません

for currentNode in nodeTable:
    currentDistance = nodeTable[currentNode].distFromSource + network[currentNode][nearestNeighbour] #gets current distance from source

代わりに次のように書く必要があります。

for currentNode in nodeTable:
    currentDistance = currentNode.distFromSource + network[currentNode][nearestNeighbour]

ネットワークがキーのノードを持つ辞書であると仮定すると、それは正常に機能します。

于 2011-03-07T20:15:24.707 に答える