开发者

Python - Calculating Distance in Dijkstra

I am having some trouble in determining the distance of each node from the start node, or rather getting any information back at all. I get no output from my function, attached in the following link.

#Values to assign to each node
class Node:
     distFromSource = infinity
     previous = invalid_node
     visited = False

#for each node assign default values    
def populateNodeTa开发者_开发问答ble(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

My logic is, at least in my mind, correct; however, I don't get as much as an error message when the code is run.


You're setting nearestNeighbour to be an empty list, and then you're looping over it with for currentNode in nearestNeighbour -- which does nothing, because the list is empty -- and then you're returning from the function.

(I assume tentativeDistance is the function you're calling and seeing nothing from.)


You should rethink your algorithm design. Try looking up a pseudocode definition of Dijkstra's algorithm and implementing that in Python. In particular, you should think about the control flow in your program.

You might want to have a look at this cookbook recipe for a Python implementation of Dijkstra and see if you can understand it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜