Python Forum
need help with some explanation - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: need help with some explanation (/thread-2544.html)



need help with some explanation - vincelim99 - Mar-24-2017

http://imgur.com/a/Ijcbi
n = int(input("Enter the number of vertices you want"))
FileName = input("Please input name of file:")
edgeFile = open(FileName)

#empty adj.list
adjList = n*[0]
for i in range(n):
    adjList[i]=[]

#adj.list
for line in edgeFile:
    edgePoint = line.split()
    adjList[int(edgePoint[0])].append(int(edgePoint[1]))
    adjList[int(edgePoint[1])].append(int(edgePoint[0]))

edgeFile.close
print(adjList)
This code was given by lecturer and it works and gives the result : [[1, 2], [0, 2, 3], [1, 0], [1]]
I've been trying to understand why it gives output like that,i know those are the vertices that connects but i just don't know how the table of [[1, 2], [0, 2, 3], [1, 0], [1]] is produced.
Moderator Larz60+: Added code tags. Please use in the future





RE: need help with some explanation - zivoni - Mar-24-2017

Before your for loop. adjList is initialized as [[], [], [], []]. In every pass of a loop one line is read from file, converted to a pair of ints and "processed".

First line is 0 1, that means there is an edge connecting vertex 0 with vertex 1, so 1 is appended to adj[0] list (to note that vertex 0 is connected to vertex 1), and 0 is appended to adj[1] list (again, to note that 1 is connected to 0). So after first run of loop block adjList is [[1], [0], [], []].

In second run edge 2 1 is added, so adjList becomes [[1], [0, 2], [1], []]. In remaining two runs edges 0 2 and 1 3 are added, so when for loop ends, adjList is [[1, 2], [0, 2, 3], [1, 0], [1]]

And , "need help with some explanation" is a terrible thread title, title actually saying something would be much better - for example "making graph from file" or "how edges convert to a list".


RE: need help with some explanation - nilamo - Mar-24-2017

In addition, you should use with blocks for file handling, to avoid things like the error in your code. (you never close the file you opened)