def test_uniform_search(self): print("Test uniform") cases = ["A B 20\nA D 1\nB C 1\nD C 1".split("\n"), "A B 1\nA D 20\nB C 1\nD C 1".split("\n")] known_path = [["A", "D", "C"], ["A", "B", "C"]] for cidx, case in enumerate(cases): search = SearchAlgo(case) path = search.uniform("A", "C") for idx, node in enumerate(path): self.assertEquals(node.name, known_path[cidx][idx]) path = search.uniform("C", "C") self.assertEquals(len(path), 1) self.assertEquals(path[0].name, "C")
def test_breadth_first_search(self): print("Test breadth") text = "A B 1\nB C 1\nC B 1".split("\n") search = SearchAlgo(text) path = search.breadth("A", "C") known_path = ["A", "B", "C"] known_cost = 2 for idx, node in enumerate(path): self.assertEquals(node.name, known_path[idx]) self.assertEquals(SearchNode.cost(path[0], path[1:]), known_cost) path = search.breadth("C", "C") self.assertEquals(len(path), 1) self.assertEquals(path[0].name, "C")
def test_breadth_first_search(self): print('Test breadth') text = 'A B 1\nB C 1\nC B 1'.split('\n') search = SearchAlgo(text) path = search.breadth('A', 'C') known_path = ['A', 'B', 'C'] known_cost = 2 for idx, node in enumerate(path): self.assertEquals(node.name, known_path[idx]) self.assertEquals(SearchNode.cost(path[0], path[1:]), known_cost) path = search.breadth('C', 'C') self.assertEquals(len(path), 1) self.assertEquals(path[0].name, 'C')
def main(): """ Main function, starts all the stuff :return: """ # Figure if the arguments are good args = sys.argv[1:] if len(args) < 5: print('Usage: Search.py <input> <output> <start> <end> <type>') return -1 input_file = args[0] output_file = args[1] start = args[2] end = args[3] search_type = args[4] # Check args if not isinstance(input_file, str) or not isinstance(output_file, str): print('One of your files are not strings') return -1 # Check if input exists if not os.path.exists(input_file): print('Input file does not exist!') return -1 # Generate the graph search = None with open(input_file) as data: search = SearchAlgo(data.readlines()) print('Graph built with:', len(search), 'nodes') # See if nodes we're searching for are in the graph if not search.node_exists(start) or not search.node_exists(end): print('One of the given nodes were not in the graph!') return -1 # Start searching path = [] if search_type == 'breadth': print('Breadth first search:', start, '->', end) path = search.breadth(start, end) elif search_type == 'depth': print('Depth first search:', start, '->', end) path = search.depth(start, end) elif search_type == 'uniform': print('Uniform first search:', start, '->', end) path = search.uniform(start, end) # Print it out to the file if path: print_path(output_file, path) else: print_path(output_file, []) print('No path returned')