Issue
I have data in the form of:
A=B=11
A=C=6
A=D=5
B=C=19
B=D=17
C=D=6
But I'd like to convert this into this format:
graph= [[ 0, 10, 15, 20 ],
[ 10, 0, 35, 25 ],
[ 15, 35, 0, 30 ],
[ 20, 25, 30, 0 ]]
How is this achieved? I'm aware of how multi-dimensional arrays work however constructing this matrix using python is quite confusing
Solution
You can use a dictionary to make an adjacency list. Then enumerate the keys of that dictionary to define an index for each key. Then finally copy the weights into the final matrix structure:
nodes = {}
for line in open("input.txt").read().splitlines():
a, b, weight = line.split("=")
nodes.setdefault(a, []).append((b, int(weight)))
nodes.setdefault(b, []).append((a, int(weight)))
n = len(nodes)
key2index = { key: i for i, key in enumerate(nodes.keys()) }
graph = [[0] * n for _ in range(n)]
for a, edges in nodes.items():
row = graph[key2index[a]]
for b, weight in edges:
row[key2index[b]] = weight
print(graph)
A zero in the matrix denotes there is no edge, like is the case in your example on the main diagonal of the matrix (i.e. your example graph has no "loops").
Comment
As you asked in a deleted comment to skip the first line of the file, here is the code adapted to do just that:
nodes = {}
lines = open("input.txt").read().splitlines()
for line in lines[1:]:
a, b, weight = line.split("=")
nodes.setdefault(a, []).append((b, int(weight)))
nodes.setdefault(b, []).append((a, int(weight)))
n = len(nodes)
key2index = { key: i for i, key in enumerate(nodes.keys()) }
graph = [[0] * n for _ in range(n)]
for a, edges in nodes.items():
row = graph[key2index[a]]
for b, weight in edges:
row[key2index[b]] = weight
print(graph)
Answered By - trincot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.