def _simple(self, V: int, p: float) -> Digraph: if p < 0.0 or p > 1.0: raise ValueError("Probability must be between 0 and 1") g = Digraph(V) for v in range(V): for w in range(V): if v != w: if random.uniform() < p: g.add_edge(v, w) return g
def main(): import os from stdlib.utils.inn import In dirpath = os.getcwd() inn = In('{0}/tests/tinyDG.txt'.format(dirpath)) g = Digraph(inn=inn) dfs = DepthFirstOrder(G=g) print(" v pre post") print("--------------") s = '' for v in range(g.V): s += '\t{} \t{} \t{}\n'.format(v, dfs.pre(v), dfs.post(v)) s += 'Preorder: ' for v in dfs.pre(): s += '{} '.format(v) s += '\nPostorder: ' for v in dfs.post(): s += '{} '.format(v) s += '\nReverse postorder: ' for v in dfs.reverse_post(): s += '{} '.format(v) print(s)
def simple(self, V: int, E: int) -> Digraph: if E > V * (V - 1): raise ValueError("Too many edges") if E < 0: raise ValueError("Too few edges") g = Digraph(V) s = set() while g.E < E: v = random.uniform(V) w = random.uniform(V) e = Edge(v, w) if v != w and e not in s: s.add(e) g.add_edge(v, w) return g
def dag(self, V: int, E: int) -> Digraph: if E > V * (V - 1) / 2: raise ValueError("Too many edges") if E < 0: raise ValueError("Too few edges") g = Digraph(V) s = set() vertices = [i for i in range(V)] random.shuffle(vertices) while g.E < E: v = random.uniform(V) w = random.uniform(V) e = Edge(v, w) if v < w and e not in s: s.add(e) g.add_edge(vertices[v], vertices[w]) return g
def tournament(self, V: int) -> Digraph: g = Digraph(V) for v in range(g.V): for w in range(v + 1, g.V): if random.uniform() < 0.5: g.add_edge(v, w) else: g.add_edge(w, v) return g
def dfs(self, v: int, G: Digraph = None, EWG: EdgeWeightedDigraph = None): if not G and not EWG: raise ValueError("You have to provide a digraph or edge weighted digraph") self._marked[v] = True self._pre[v] = self._pre_counter self._pre_counter += 1 self._preorder.enqueue(v) if G: for w in G.adj(v): if not self._marked[w]: self.dfs(w, G=G) elif EWG: for e in EWG.adj(v): w = e.to() if not self._marked[w]: self.dfs(w, EWG=EWG) self._postorder.enqueue(v) self._post[v] = self._post_counter self._post_counter += 1
def main(): import os from stdlib.utils.inn import In dir_path = os.getcwd() inn = In('{0}/tests/tinyDG.txt'.format(dir_path)) s = 1 g = Digraph(inn=inn) dfs = DepthFirstDirectedPaths(g, s) string = '' for v in range(g.V): if dfs.has_path_to(v): string += '{0} to {1}: '.format(s, v) for x in dfs.path_to(v): if x == s: string += x.__str__() else: string += "-{0}".format(x) string += '\n' else: string += "{0} to {1}: not connected\n".format(s, v) print(string)
def __dfs(self, G: Digraph, v: int) -> None: self._marked[v] = True for w in G.adj(v): if not self._marked[w]: self._edge_to[w] = v self.__dfs(G, w)