Calculate the complexity of this code class Digraph: def init(self): self.edges = {} def…
- User
Calculate the complexity of this code class Digraph: def init(self): self.edges = {}
codedef add_vertex(self, v): if v not in self.edges: self.edges[v] = set() def add_edge(self, v, w): self.add_vertex(v) self.add_vertex(w) self.edges[v].add(w) def adj(self, v): return self.edges.get(v, set()) def vertices(self): return self.edges.keys()class SAP: def init(self, graph): self.graph = graph
codedef _bfs(self, sources_v, sources_w): dist_v = {v: float('inf') for v in self.graph.vertices()} dist_w = {v: float('inf') for v in self.graph.vertices()} queue = [] for s in sources_v: if s in dist_v: dist_v[s] = 0 queue.append((s, 'v')) for s in sources_w: if s in dist_w: dist_w[s] = 0 queue.append((s, 'w')) shortest = float('inf') ancestor = -1 while queue: v, source = queue.pop(0) current_dist = dist_v if source == 'v' else dist_w opposite_dist = dist_w if source == 'v' else dist_v if opposite_dist[v] != float('inf'): total_dist = current_dist[v] + opposite_dist[v] if total_dist < shortest: shortest = total_dist ancestor = v for w in self.graph.adj(v): if current_dist[w] == float('inf'): current_dist[w] = current_dist[v] + 1 queue.append((w, source)) return shortest, ancestor def length(self, v, w): shortest, _ = self._bfs([v], [w]) return -1 if shortest == float('inf') else shortest def ancestor(self, v, w): _, ancestor = self._bfs([v], [w]) return ancestor def length_in_list(self, v_list, w_list): shortest, _ = self._bfs(v_list, w_list) return -1 if shortest == float('inf') else shortest def ancestor_in_list(self, v_list, w_list): _, ancestor = self._bfs(v_list, w_list) return ancestor - Assistant
- User
Does this code meet these criterias? ¢Your data type must use a space that is linear in the input size (the size of the synsets and hyperlinks in the files). ¢The constructor should run in linear time. ¢The is_noun() method should work with no more than logarithmic time to the number of nouns. ¢distance() and sap() should work in linear time.
- Assistant
Let's examine whether the code meets the specified criteria:
1. Linear Space Requirement
The code uses dictionaries and sets to store synsets and graph edges:
-
Synsets Dictionary: Stores each synset by its ID, with space requirements proportional to the number of synsets.
-