开发者

Int Object Is Not Iterable

开发者 https://www.devze.com 2023-02-13 05:30 出处:网络
I have come across a problem that I don\'t know how to resolve involving Dijkstra\'s algorithm - here is my code:

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:

for i in nodeTable:

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 ...


How about for i in range(numNodes) ... numNodes is just a number, not an array of numbers, which is what you are after.


If you want to iterate over the element indexes, use for i, _ in enumerate(nodeTable)

If you want to access the element itself, too, use a real name instead of _

0

精彩评论

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