The question asks: A graph can be represented in a file by listing one link per line, with each link represented by a pair of nodes. Write a function that reads such a file and returns an adjacency list (as a dictionary) for the graph. Notice that, for each line AB in the file, your function will need to insert node B into the list of neighbors A and insert node A into the list of neighbors of B . Example of a possible file:
graph.txt
A B
A C
A D
B E
C D
C E
I expect the final list to look something like this:
adjList = {
A: [B, C, D],
B: [A, E],
C: [A, D, E],
D: [A, C],
E: [B, C],
}
You can use defaultdict to answer this question. I wrote the code and it is working but you may like to think about it first.
dictAdjacency=defaultdict(list)
with open('C:/graph.txt') as readObj:
lines=readObj.readlines()
for line in lines:
tempList=line.rstrip('\n').split(' ')
dictAdjacency[tempList[0]].append(tempList[1])
dictAdjacency[tempList[1]].append(tempList[0])
print(dictAdjacency)
defaultdict(<class 'list'>,
{
'A': ['B', 'C', 'D'],
'B': ['A', 'E'],
'C': ['A', 'D', 'E'],
'D': ['A', 'C'],
'E': ['B', 'C']
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.