python - Performing a breadth first search using a given class -
using following (very badly written) class:
class graph: def __init__(self, graph_string): self.graph_string = [] graph_string = graph_string.splitlines() in graph_string: = (i.split()) self.graph_string.append(i) directed_helper = self.graph_string[0] directed_score = directed_helper[0] weighted_helper = self.graph_string[0] weighted_score = weighted_helper[1] self.weighted = weighted_score self.directed = directed_score self.graph_string.pop(0) if self.directed == ("d"): self.directed = true elif self.directed == ("u"): self.directed = false if self.weighted == ("w"): self.weighted = true elif self.weighted != ("w"): self.weighted = false if self.weighted == false: self.edge_number = graph_string[0] self.edge_number = list(self.edge_number) self.edge_number = self.edge_number[2] self.edge_number = int(self.edge_number) self.adjacency_list = [[] _ in range(self.edge_number)] elif self.weighted == true: self.edge_number = graph_string[0] self.edge_number = list(self.edge_number) self.edge_number = self.edge_number[4] self.edge_number = int(self.edge_number) self.adjacency_list = [[] _ in range(self.edge_number)] if self.weighted == false: if self.directed == true: s in self.graph_string: first_element = s[0] first_element = int(first_element) second_element = s[1] second_element = int(second_element) self.adjacency_list[first_element].append((second_element, none)) elif self.directed == false: t in self.graph_string: first_element = t[0] first_element = int(first_element) second_element = t[1] second_element = int(second_element) self.adjacency_list[first_element].append((second_element, none)) self.adjacency_list[second_element].append((first_element, none)) elif self.weighted == true: if self.directed == true: t in self.graph_string: first_element = t[0] first_element = int(first_element) second_element = t[1] second_element = int(second_element) third_element = t[2] third_element = int(third_element) self.adjacency_list[first_element].append((second_element, third_element)) if self.directed == false: t in self.graph_string: first_element = t[0] first_element = int(first_element) second_element = t[1] second_element = int(second_element) third_element = t[2] third_element = int(third_element) self.adjacency_list[first_element].append((second_element, third_element)) self.adjacency_list[first_element].append((first_element, third_element)) (self.adjacency_list)
i wish use adjacency list outputs given inputted graph, write new function:
bfs_tree(graph, start)
which performs breadth-first search returns parents array @ end of search. example input:
graph_string = """\ d 2 0 1 """ print(bfs_tree(graph(graph_string), 0))
the code should return:
[none, 0]
or given:
graph_string = """\ u 7 1 2 1 5 1 6 2 3 2 5 3 4 4 5 """ print(bfs_tree(graph(graph_string), 1))
the output should be:
[none, none, 1, 2, 5, 1, 1]
any appreciated :)
Comments
Post a Comment