Use a dynamic input from file

Viewed 81

I want to create a graph from the below points:

edges = [
('X', 'A', 7),
('X', 'B', 2),
('X', 'C', 3),
('X', 'E', 4),
('A', 'B', 3),
('A', 'D', 4),
('B', 'D', 4),
('B', 'H', 5),
('C', 'L', 2)
]

where the first element in each line works as a source point, the second element works as a destination and the third point works as a distance between the 2 points. Example - In first line X is the source, A is the destination and 7 is the weight of the edges between the 2 nodes. When I use this directly in the code, I get the required graph. However, I have to take the input from an external text file and use it in the code where the input will be like

A / B / 3
A / D / 4
B / D / 4
B / H / 5
C / L / 2

This is the code that we have used till now:-

from collections import defaultdictclass Graph():
def __init__(self):
self.edges = defaultdict(list)
self.weights = {}
def add_edge(self, from_node, to_node, weight):
self.edges[from_node].append(to_node)
self.edges[to_node].append(from_node)
self.weights[(from_node, to_node)] = weight
self.weights[(to_node, from_node)] = weight
graph = Graph()
edges = [
('X', 'A', 7),
('X', 'B', 2),
('X', 'C', 3),
('X', 'E', 4),
('A', 'B', 3),
('A', 'D', 4),
('B', 'D', 4),
('B', 'H', 5),
('C', 'L', 2),
]
for edge in edges:
graph.add_edge(*edge)

So, I want some clarification on how to add the edges from the input text file and use it in our python code.

1 Answers

I have created a text file called test.txt with the following content.

A / B / 3
A / D / 4
B / D / 4
B / H / 5
C / L / 2

Now, we just read this file line by line and split by the character / and put the result in a 3-tuple and each 3-tuple will be appended to an array called edges.

with open('test.txt') as f:
    lines = f.readlines()

edges = []
for line in lines:
    t = line.strip().split(' / ')
    s = (*tuple(t[:-1]),int(t[2]))
    edges.append(s)
print(edges)

which yields the following output.

[('A', 'B', 3), ('A', 'D', 4), ('B', 'D', 4), ('B', 'H', 5),('C', 'L', 2)]
Related