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.