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.")
def __init__(self, filename, delimiter): """Initializes a graph 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 = Graph(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)
x = v while self._dist_to[x] != 0: path.push(x) x = self._edgeTo[x] path.push(x) return path if __name__ == "__main__": import sys from itu.algs4.stdlib import stdio from itu.algs4.graphs.graph import Graph from itu.algs4.stdlib.instream import InStream In = InStream(sys.argv[1]) G = Graph.from_stream(In) s = int(sys.argv[2]) bfs = BreadthFirstPath(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)
while w != self._s: path.push(w) # find w's parent link vertex,recursively until reach source. w = self._edgeTo[w] path.push(self._s) return path if __name__ == "__main__": from itu.algs4.stdlib import stdio from itu.algs4.graphs.graph import Graph from itu.algs4.stdlib.instream import InStream import sys In = InStream(sys.argv[1]) G = Graph.from_stream(In) s = int(sys.argv[2]) dfs = DepthFirstPath(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)
return self._marked[v] def count(self) -> int: """ return how many vertices connected to s :return: """ return self._count if __name__ == '__main__': from itu.algs4.graphs.graph import Graph from itu.algs4.stdlib.instream import InStream from itu.algs4.stdlib import stdio import sys In = InStream(sys.argv[1]) G = Graph.from_stream(In) s = int(sys.argv[2]) search = DepthFirstSearch(G, s) for v in range(G.V()): if search.marked(v): stdio.writef("%i ", v) stdio.writeln() if search.count() != G.V(): stdio.writeln("G is NOT a connected graph") else: stdio.writeln("G is a connected graph")
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 itu.algs4.graphs.edge_weighted_graph import EdgeWeightedGraph from itu.algs4.stdlib import stdio from itu.algs4.stdlib.instream import InStream 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 itu.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, 0.5)) stdio.writef("%7.5f ", gaussian(9.0, 0.2)) stdio.writef("%2d ", discrete([0.5, 0.3, 0.1, 0.1])) stdio.writeln()
i = 1 while i < self.size(): if self._keys[i] < self._keys[i - 1]: return False i += 1 return True def _rank_check(self): # check that rank(select(i)) = i for i in range(self.size()): if i != self.rank(self.select(i)): return False for i in range(self.size()): if self._keys[i] != self.select(self.rank(self._keys[i])): return False return True if __name__ == "__main__": from itu.algs4.stdlib import stdio st = BinarySearchST() 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))
""" self._validateVertex(v) return self._keys[v] def graph(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 = SymbolGraph(filename, delimiter) graph = sg.graph() 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)
#!/usr/bin/env python3 import sys from itu.algs4.fundamentals.stack import Stack from itu.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[str] = 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())
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 itu.algs4.stdlib.instream import InStream from itu.algs4.stdlib import stdio from itu.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) -> str: out = '{' for elem in self: out += '{}, '.format(elem) return out + '}' # start of the script itself if __name__ == '__main__': import sys from itu.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[str] = 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 count(self): return self._count if __name__ == "__main__": import sys from itu.algs4.fundamentals.queue import Queue from itu.algs4.graphs.graph import Graph from itu.algs4.stdlib import stdio from itu.algs4.stdlib.instream import InStream 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()
def _main(): """ For testing. """ import sys from itu.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()
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 itu.algs4.stdlib.instream import InStream from itu.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()