I have come across a problem that I don’t know how to resolve involving Dijkstra’s algorithm – here is my code:
infinity = 1000000
invalid_node = -1
#startNode = 0
class Node:
distFromSource = infinity
previous = invalid_node
visited = False
def populateNodeTable():
nodeTable = []
f = open("twoDArray.txt", "r")
for line in f.readlines(): #get number of nodes from file
nodeTable.append(line.split(',')) # Create matrix of weights
numNodes = len(nodeTable) # Count nodes
print numNodes
#for all nodes in text file, set visited to false, distFromSource to infinity & predecessor to none
**for i in numNodes:
nodeTable.append(Node(i))**
#nodeTable.append(Node())
nodeTable[startNode].distFromSource = 0
print nodeTable
if __name__ == "__main__":
populateArray()
populateNodeTable()
When I run this code I get the following error:
Traceback (most recent call last):
File "2dArray.py", line 63, in <module>
populateNodeTable()
File "2dArray.py", line 18, in populateNodeTable
for i in numNodes:
TypeError: 'int' object is not iterable
I am not sure how I rectify this error (the section between the asterix) – what I am trying to do is to read my text file which is just a series of integers separated by commas, and count the number of nodes within that text file
Each node will then be assigned the values in the Node class
Try this:
why are you trying to iterate over
numNodes? You just defined one line above as the length of the table.But appending to the same table in the loop doesn’t make sense. And it does not work together with the code that reads the file. Also the Node class isn’t usable at all …