def read_graph_from_file(file_name): '''Read graph from a file''' file = open(file_name, 'r') file_list = file.readlines() vertices = file_list[1].rstrip().split(',') valid_types = 'gGdD' graph_type = '' directed = False weighted = False edges_list = [] if file_list[0].rstrip() in valid_types: graph_type = file_list[0].upper() else: raise ValueError('G or D is not specified') if graph_type == 'D': directed = True for item in range(2, len(file_list)): edge = file_list[item].rstrip().replace('(', '').replace(')', '').split(',') if len(edge) == 3: weighted = True edges_list.append(edge) graph = Graph(weighted, directed) for edge in edges_list: if weighted: graph.add_weighted_edge(int(edge[0]), int(edge[1]), int(edge[2])) else: graph.add_edge(int(edge[0]), int(edge[1])) return graph
def test_get_edge_list(self): g = Graph(weighted=True, directed=False) g.add_weighted_edge('A', 'B', 5) g.add_weighted_edge('C', 'D', 3) g.add_weighted_edge('E', 'F', 2) g.add_weighted_edge('G', 'H', 1) self.assertCountEqual(g.get_edge_list(), [('A', 'B', 5), ('C', 'D', 3), ('E', 'F', 2), ('G', 'H', 1)])