Hey,
I have a function, though it's not working as it should be. My program is Dijkstra's algorithm, and I am trying to build a list of a node's nearest neighbours using info contained in a text file of the network (7 nodes in this case), in the form:
0,2,4,1,6,0,0
2,0,0,0,5,0,0
4,0,0,0,5,5,0
1,0,0,0,1,1,0
6,5,0,1,0,5,5
0,0,5,1,5,0,0
0,0,0,0,5,0,0
This is the relevant parts of my code:
infinity = 1000000
invalid_node = -1
startNode = 0
#Values to assign to each node
class Node:
distFromSource = infinity
previous = invalid_node
visited = False
#read in all network nodes
#node = the distance values between nodes
def network():
f = open ('network.txt', 'r')
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:
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
#find the nearest neighbour to a particular node
def nearestNeighbour(nodeTable, theNetwork):
listOfNeighbours = []
nodeIndex = 0
for node in nodeTable:
if node != 0 and Node.visited == False:
nearestNode = node[theNetwork]
listOfNeighbours.append(nearestNode)
nodeIndex +=1
print listOfNeighbours
return listOfNeighbours
currentNode = startNode
if __name__ == "__main__":
nodeTable = populateNodeTable()
theNetwork = network()
nearestNeighbour(nodeTable, theNetwork)
tentativeDistance(theNetwork, nodeTable, nodeIndex)
I am getting the error message:
nearestNode = node[theNetwork]
AttributeError: Node instance has no attribute '__getitem__'
Even before I had any error messages, I was simply getting this output from the nearestNeighbour function:
[[0, 1, 2, 3, 4, 5, 6]]
So, yeah, I am stuck on how I can correctly populate the listOfNeighbours list correctly :s