开发者

Python - 'object cannot be interpreted as an index' Error

I am having an error that I don't understand in my Dijkstra Algorithm code - here is the error message:

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

Here is my code:

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 curren开发者_如何学GotDistance != 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())

My first function performs correctly, and my logic is correct for my second function though searching online for the solution has proved fruitless


Given the way for loops work in Python, you don't have to write

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

You should instead write:

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

Assuming network is a dictionary with nodes for keys, that will work fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜