I am absolutely useless with python and I’m struggling to do what seems to be simple things.
I need to read a text file which contains a network routing table which contains the distance between each node on the network (below)
0,2,4,1,6,0,0
2,0,0,0,5,0,0
4,0,0,0,0,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
I then need to assign it to a two dimensional array which I have done with the code i have written below..
Network = []
NodeTable = []
def readNetwork():
myFile = open('network.txt','r')
for line in myFile.readlines():
line.strip(' \n' '\r')
line = line.split(',')
line = [int(num) for num in line]
Network.append(line)
Once that has been done I then need to iterate through the Network array and add each horizontal line to another array which will hold information about the nodes, but as far as I have been able to get with that is here:
class Node(object):
index = #Needs to start from A and increase with each node
previousNode = invalid_node
distFromSource = infinity
visited = False
NodeTable.append(Node())
So that array will be initialised as:
A invalid_node infinity False
B invalid_node infinity False
C invalid_node infinity False
...
etc
Could anyone give me a hand with creating each node in the NodeTable array?
Redundant line
Strings in Python are immutable, thus with the following line:
you are only getting a copy of the
linestring, stripped of some characters, but you do not assign it to anything. Change it into:As DSM pointed out in the comments, it will not change much, as
intwill just ignore redundant whitespaces.Mapping string to
intsYou also are mapping strings to
ints like that:which could be replaced by clearer:
and should give you some slight performance gain also. To shorten your code, you can also replace the following lines:
with the following:
How to increase
Node‘sindexattribute with each instanceThis could be done like that:
As you can see
baseindexis attached to the class, andindexis attached to the class’s instance. I suggest you should attach every instance-specific variable to the instance, as shown in the example above.Adding
Nodeinto the list as listOne of the easiest ways to insert it as list into another list, is to add a method returning it as list (see
as_list()method):so you should be able to add nodes like this:
But remember – after doing the above, you will not get list of
Nodeinstances, you will get list of lists.