def read_graph_from_file(file_name: str): try: with open(file_name) as graph_file: graph_temp = Graph() for line in graph_file.readlines(): lst = line.split() if len(lst) == 2: if graph_temp.is_vertex(lst[0]): graph_temp.start = lst[0] if graph_temp.is_vertex(lst[1]): graph_temp.end = lst[1] elif len(lst) == 3: vertex_1 = lst[0] vertex_2 = lst[1] edge_weight = int(lst[2]) if edge_weight > 0: graph_temp.add_edge(vertex_1.strip(), vertex_2.strip(), edge_weight) else: print("ERROR: Wrong file format.") return Graph() if graph_temp.start is None: graph_temp.start = graph_temp.vertices[list( graph_temp.vertices.keys())[0]] if graph_temp.end is None: graph_temp.end = graph_temp.vertices[list( graph_temp.vertices.keys())[-1]] return graph_temp except FileNotFoundError: print("ERROR: File ", file_name, " not found.") print("Current folder: " + str(Path.cwd())) return None
def test_brute_force(self): graph1 = Graph() graph1.add_edge("A", "B", 1) graph1.add_edge("A", "C", 1) graph1.add_edge("B", "D", 9) graph1.add_edge("C", "D", 1) graph1.end = "D" graph1.start = "A" path = brute_force(graph1) self.assertListEqual(path[0], ["A", "C", "D"]) self.assertEqual(path[1], 2)