def __init__(self, filename, delimiter): """ Initializes a digraph from a file using the specified delimiter. Each line in the file contains the name of a vertex, followed by a list of the names of the vertices adjacent to that vertex, separated by the delimiter. :param filename: the name of the file :param delimiter: the delimiter between fields """ self._st = BinarySearchST() # string -> index # First pass builds the index by reading strings to associate # distinct strings with an index stream = InStream(filename) while not stream.isEmpty(): a = stream.readLine().split(delimiter) for i in range(len(a)): if not self._st.contains(a[i]): self._st.put(a[i], self._st.size()) stdio.writef("Done reading %s\n", filename) # inverted index to get keys in an array self._keys = [None] * self._st.size() # index -> string for name in self._st.keys(): self._keys[self._st.get(name)] = name # second pass builds the graph by connecting first vertex on each # line to all others self._graph = Digraph(self._st.size()) # the underlying graph stream = InStream(filename) while stream.hasNextLine(): a = stream.readLine().split(delimiter) v = self._st.get(a[0]) for i in range(1, len(a)): w = self._st.get(a[i]) self._graph.add_edge(v, w)
def main(args): """ Reads in a social network from a file, and then repeatedly reads in individuals from standard input and prints out their degrees of separation. Takes three command-line arguments: the name of a file, a delimiter, and the name of the distinguished individual. Each line in the file contains the name of a vertex, followed by a list of the names of the vertices adjacent to that vertex, separated by the delimiter. :param args: the command-line arguments """ filename = args[1] delimiter = args[2] source = args[3] sg = SymbolGraph(filename, delimiter) G = sg.graph() if not sg.contains(source): stdio.writeln("{} not in database".format(source)) return s = sg.index_of(source) bfs = BreadthFirstPaths(G, s) while not stdio.isEmpty(): sink = stdio.readLine() if sg.contains(sink): t = sg.index_of(sink) if bfs.has_path_to(t): for v in bfs.path_to(t): stdio.writef("\t%s\n", sg.name_of(v)) else: stdio.writeln("\tNot connected") else: stdio.writeln("\tNot in database.")
""" self._validateVertex(v) return self._keys[v] def digraph(self): return self._graph def _validateVertex(self, v): # throw an IllegalArgumentException unless 0 <= v < V V = self._graph.V() if v < 0 or v >= V: raise ValueError("vertex {} is not between 0 and {}".format( v, V - 1)) if __name__ == "__main__": import sys filename = sys.argv[1] delimiter = sys.argv[2] sg = SymbolDigraph(filename, delimiter) graph = sg.digraph() while stdio.hasNextLine(): source = stdio.readLine() if sg.contains(source): s = sg.index_of(source) for v in graph.adj(s): stdio.writef("\t%s\n", sg.name_of(v)) else: stdio.writef("input not contain '%i'", source)
return path def _validateVertex(self, v): # throw an ValueError unless 0 <= v < V V = len(self._marked) if v < 0 or v >= V: raise ValueError("vertex {} is not between 0 and {}".format( v, V - 1)) if __name__ == "__main__": from algs4.stdlib import stdio from algs4.graphs.graph import Graph from algs4.stdlib.instream import InStream import sys In = InStream(sys.argv[1]) G = Graph.from_stream(In) s = int(sys.argv[2]) dfs = DepthFirstPaths(G, s) for v in range(G.V()): if dfs.has_path_to(v): stdio.writef("%d to %d: ", s, v) for x in dfs.path_to(v): if x == s: stdio.write(x) else: stdio.writef("-%i", x) stdio.writeln() else: stdio.writef("%d to %d: not connected\n", s, v)
# short circuit if cycle already found if self._cycle is not None: return if not self._marked[w]: self._edgeTo[w] = v self._dfs(G, v, w) elif w != u: self._cycle = Stack() x = v while x != w: self._cycle.push(x) x = self._edgeTo[x] self._cycle.push(w) self._cycle.push(v) if __name__ == "__main__": import sys from algs4.stdlib.instream import InStream from algs4.stdlib import stdio from algs4.graphs.graph import Graph In = InStream(sys.argv[1]) G = Graph.from_stream(In) finder = Cycle(G) if finder.has_cycle(): for v in finder.cycle(): stdio.writef("%i ", v) stdio.writeln() else: stdio.writeln("Graph is acyclic")
x = f.either() y = f.other(x) if f != e: uf.union(x, y) # check that e is min weight edge in crossing cut for f in G.edges(): x = f.either() y = f.other(x) if not uf.connected(x, y): if f.weight() < e.weight(): error = "Edge {} violates cut optimality conditions".format( f) print(error, file=sys.stderr) return False return True if __name__ == "__main__": import sys from algs4.stdlib.instream import InStream from algs4.stdlib import stdio from algs4.graphs.edge_weighted_graph import EdgeWeightedGraph In = InStream(sys.argv[1]) G = EdgeWeightedGraph.from_stream(In) mst = LazyPrimMST(G) for e in mst.edges(): stdio.writeln(e) stdio.writef("%.5f\n", mst.weight())
def _main(): """ For testing. """ import sys from algs4.stdlib import stdio seed(1) n = int(sys.argv[1]) for i in range(n): stdio.writef(' %2d ' , uniformInt(10, 100)) stdio.writef('%8.5f ' , uniformFloat(10.0, 99.0)) stdio.writef('%5s ' , bernoulli()) stdio.writef('%5s ' , binomial(100, .5)) stdio.writef('%7.5f ' , gaussian(9.0, .2)) stdio.writef('%2d ' , discrete([.5, .3, .1, .1])) stdio.writeln()
e = self._edge_to[e.from_vertex()] return path def _validate_vertex(self, v): # raise an ValueError unless 0 <= v < V V = len(self._dist_to) if v < 0 or v >= V: raise ValueError("vertex {} is not between 0 and {}".format( v, V - 1)) if __name__ == "__main__": import sys from algs4.stdlib.instream import InStream from algs4.stdlib import stdio from algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph In = InStream(sys.argv[1]) s = int(sys.argv[2]) G = EdgeWeightedDigraph.from_stream(In) # find shortest path from s to each other vertex in DAG sp = AcyclicSP(G, s) for v in range(G.V()): if sp.has_path_to(v): stdio.writef("%d to %d (%.2f) ", s, v, sp.dist_to(v)) for e in sp.path_to(v): stdio.writef("%s\t", e.__repr__()) stdio.writeln() else: stdio.writef("%d to %d no path\n", s, v)
yield current.item current = current.next def __repr__(self): out = '{' for elem in self: out += '{}, '.format(elem) return out + '}' # start of the script itself if __name__ == '__main__': import sys from algs4.stdlib import stdio if len(sys.argv) > 1: try: sys.stdin = open(sys.argv[1]) except IOError: print("File not found, using standard input instead") bag = Bag() while not stdio.isEmpty(): item = stdio.readString() bag.add(item) stdio.writef("size of bag = %i\n", bag.size()) for s in bag: stdio.writeln(s)
def _check(self, G, s): # check optimality conditions for singe source # check that the distance of s = 0 if (self._dist_to[s] != 0): stdio.writef("distance of source %i to itself = %i\n", s, self._dist_to[s]) return False # check that for each edge v-w dist[w] <= dist[v] + 1 # provided v is reachable from s for v in range(G.V()): for w in G.adj(v): if self.has_path_to(v) != self.has_path_to(w): stdio.writef("edge %i-%i\n", v, w) stdio.writef("has_path_to(%i) = %i\n", v, self.has_path_to(v)) stdio.writef("has_path_to(%i) = %i\n", w, self.has_path_to(w)) return False if self.has_path_to(v) and (self._dist_to[w] > self._dist_to[v] + 1): stdio.writef("edge %i-%i\n", v, w) stdio.writef("dist_to[%i] = %i\n", v, self._dist_to[v]) stdio.writef("dist_to[%i] = %i\n", v, self._dist_to[w]) return False # check that v = edgeTo[w] satisfies distTo[w] = distTo[v] + 1 # provided v is reachable from s for w in range(G.V()): if not self.has_path_to(w) or w == s: continue v = self._edgeTo[w] if self._dist_to[w] != self._dist_to[v] + 1: stdio.writef("shortest path edge %i-%i\n", v, w) stdio.writef("dist_to[%i] = %i\n", v, self._dist_to[v]) stdio.writef("dist_to[%i] = %i\n", w, self._dist_to[w]) return False return True
def path_to(self, v): if not self.has_path_to(v): return None path = Stack() x = v while x != self._s: path.push(x) x = self._edgeTo[x] path.push(self._s) return path if __name__ == "__main__": import sys from algs4.stdlib import stdio from algs4.graphs.graph import Graph from algs4.stdlib.instream import InStream In = InStream(sys.argv[1]) G = Graph.from_stream(In) s = int(sys.argv[2]) bfs = BreadthFirstPaths(G, s) for v in range(G.V()): if bfs.has_path_to(v): stdio.writef("%d to %d (%d): ", s, v, bfs.dist_to(v)) for x in bfs.path_to(v): if x == s: stdio.write(x) else: stdio.writef("-%i", x) stdio.writeln() else: stdio.writef("%d to %d (-): not connected\n", s, v)
if self.n > 0 and self.n == len(self.a)/4: self.resize(len(self.a)/2) return item def __iter__(self): i = self.n -1 while i >= 0: yield self.a[i] i -= 1 if __name__ == '__main__': import sys from algs4.stdlib import stdio if len(sys.argv) > 1: try: sys.stdin = open(sys.argv[1]) except IOError: print("File not found, using standard input instead") stack = Stack() while not stdio.isEmpty(): item = stdio.readString() if not item == "-": stack.push(item) elif not stack.is_empty(): stdio.write(stack.pop() + " ") stdio.writef("(%i left on stack)\n", stack.size())
x.next = self._delete(x.next, key) return x def keys(self): """ Returns all keys in the symbol table as an Iterable. To iterate over all of the keys in the symbol table named st, use the foreach notation: for Key key in st.keys(). :returns: all keys in the symbol table """ x = self._first while x is not None: yield x.key x = x.next if __name__ == "__main__": from algs4.stdlib import stdio st = SequentialSearchST() i = 0 while not stdio.isEmpty(): key = stdio.readString() st.put(key, i) i += 1 for s in st.keys(): stdio.writef("%s %i\n", s, st.get(s))
return False return True def _validateVertex(self, v): # raise an ValueError unless 0 <= v < V V = len(self._marked) if v < 0 or v >= V: raise ValueError("vertex {} is not between 0 and {}".format( v, V - 1)) if __name__ == "__main__": from algs4.stdlib.instream import InStream from algs4.stdlib import stdio import sys In = InStream(sys.argv[1]) G = Graph.from_stream(In) stdio.writeln(G) b = Bipartite(G) if b.is_bipartite(): stdio.writeln("Graph is bipartite") for v in range(G.V()): stdio.writef("%i: %i\n", v, b.color(v)) else: stdio.writeln("Graph has an odd-length cycle: ") for x in b.odd_cycle(): stdio.writef("%i ", x) stdio.writeln()
def id(self, v): return self._id[v] def count(self): return self._count if __name__ == "__main__": import sys from algs4.fundamentals.queue import Queue from algs4.stdlib.instream import InStream from algs4.stdlib import stdio from algs4.graphs.graph import Graph In = InStream(sys.argv[1]) G = Graph.from_stream(In) cc = CC(G) # number of connected components m = cc.count() stdio.writef("%i components\n", m) # compute list of vertices in each connected component components = [Queue() for _ in range(m)] for v in range(G.V()): components[cc.id(v)].enqueue(v) # print results for i in range(m): for v in components[i]: stdio.writef("%i ", v) stdio.writeln()