def __init__(self, vertices): self._st = BinarySearchST() # string -> index # built symbol table to translate strings into indices for i in range(len(vertices)): self._st.put(vertices[i], i) # built array to translate from indices to strings self._keys = [None] * self._st.size() # index -> string for name in self._st.keys(): self._keys[self._st.get(name)] = name # initialise graph self._graph = Graph(self._st.size()) # the underlying graph
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)