示例#1
0
def evaluate():
    ops = Stack()
    vals = Stack()

    while not stdio.isEmpty():
        # Read token, push if operator
        s = stdio.readString()
        if s == "(": pass
        elif s == "+": ops.push(s)
        elif s == "-": ops.push(s)
        elif s == "*": ops.push(s)
        elif s == "/": ops.push(s)
        elif s == "sqrt": ops.push(s)
        elif s == ")":
            # Pop, evaluate and push result if token is ")"
            op = ops.pop()
            v = vals.pop()
            if op == "+": v = vals.pop() + v
            elif op == "-": v = vals.pop() - v
            elif op == "*": v = vals.pop() * v
            elif op == "/": v = vals.pop() / v
            elif op == "sqrt": v = math.sqrt(v)
            vals.push(v)
        else:
            vals.push(float(s))
    stdio.writeln(vals.pop())
示例#2
0
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()
示例#3
0
def _main():
    """
    For testing:
    """
    from algs4.stdlib import stdio
    c1 = Color(128, 128, 128)
    stdio.writeln(c1)
    stdio.writeln(c1.getRed())
    stdio.writeln(c1.getGreen())
    stdio.writeln(c1.getBlue())
示例#4
0
def write1D(a):
    """
    Write array a to sys.stdout.  First write its length. bool objects
    are written as 0 and 1, not False and True.
    """
    length = len(a)
    stdio.writeln(length)
    for i in range(length):
        # stdio.writef('%9.5f ', a[i])
        element = a[i]
        if isinstance(element, bool):
            if element == True:
                stdio.write(1)
            else:
                stdio.write(0)
        else:
            stdio.write(element)
        stdio.write(' ')
    stdio.writeln()
示例#5
0
def write2D(a):
    """
    Write two-dimensional array a to sys.stdout.  First write its
    dimensions. bool objects are written as 0 and 1, not False and True.
    """
    rowCount = len(a)
    colCount = len(a[0])
    stdio.writeln(str(rowCount) + ' ' + str(colCount))
    for row in range(rowCount):
        for col in range(colCount):
            #stdio.writef('%9.5f ', a[row][col])
            element = a[row][col]
            if isinstance(element, bool):
                if element == True:
                    stdio.write(1)
                else:
                    stdio.write(0)
            else:
                stdio.write(element)
            stdio.write(' ')
        stdio.writeln()
    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.")
        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)
示例#8
0
            # 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")
示例#9
0
            for f in self._mst:
                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())
示例#10
0
            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)
示例#11
0
def _main():
    """
    For testing.
    """
    import os
    import math
    from algs4.stdlib import stdio, instream

    _createTextAudioFile()

    stdio.writeln('Creating and playing in small chunks...')
    sps = _SAMPLES_PER_SECOND
    inStream = instream.InStream('looney.txt')
    while not inStream.isEmpty():
        pitch = inStream.readInt()
        duration = inStream.readFloat()
        hz = 440 * math.pow(2, pitch / 12.0)
        N = int(sps * duration)
        notes = []
        for i in range(N + 1):
            notes.append(math.sin(2 * math.pi * i * hz / sps))
        playSamples(notes)
    wait()

    stdio.writeln('Creating and playing in one large chunk...')
    sps = _SAMPLES_PER_SECOND
    notes = []
    inStream = instream.InStream('looney.txt')
    while not inStream.isEmpty():
        pitch = inStream.readInt()
        duration = inStream.readFloat()
        hz = 440 * math.pow(2, pitch / 12.0)
        N = int(sps * duration)
        for i in range(N + 1):
            notes.append(math.sin(2 * math.pi * i * hz / sps))
    playSamples(notes)
    wait()

    stdio.writeln('Saving...')
    save('looney', notes)

    stdio.writeln('Reading...')
    notes = read('looney')

    stdio.writeln('Playing an array...')
    playSamples(notes)
    wait()

    stdio.writeln('Playing a file...')
    playFile('looney')
    wait()

    os.remove('looney.wav')
    os.remove('looney.txt')
示例#12
0
def is_sorted(array):
    return _is_sorted(array, 0, len(array) - 1)


def _is_sorted(array, lo, hi):
    for i in range(lo + 1, hi + 1):
        if array[i] < array[i - 1]:
            return False
    return True


# print array to standard output
def show(array):
    stdio.write(" ".join(array))


if __name__ == "__main__":
    array = stdio.readAllStrings()
    sort(array)
    assert is_sorted(array)
    show(array)

    # shuffle
    stdrandom.shuffle(array)

    # display results again using select
    print()
    for i in range(0, len(array)):
        ith = str(select(array, i))
        stdio.writeln(ith)
示例#13
0
        The the rank of vertex v in the topological order -1 if the digraph is not a DAG
        
        :param v: the vertex
        :returns: the position of vertex v in a topological order of the digraph -1 if the digraph is not a DAG
        """
        self._validate_vertex(v)
        if self.has_order():
            return self._rank[v]
        else:
            return -1

    def _validate_vertex(self, v):
        # throw an IllegalArgumentException unless 0 <= v < V
        V = len(self._rank)
        if v < 0 or v >= V:
            raise ValueError("vertex {} is not between 0 and {}", v, (V - 1))


if __name__ == '__main__':
    import sys
    from algs4.stdio.instream import InStream
    from algs4.stdlib import stdio
    from algs4.graphs.symbol_digraph import SymbolDigraph

    filename = sys.argv[1]
    delimiter = sys.argv[2]
    sg = SymbolDigraph(filename, delimiter)
    topological = Topological(sg.digraph())
    for v in topological.order():
        stdio.writeln(sg.name_of(v))
示例#14
0
        Returns the number of vertices connected to the source vertex s.

        :returns: the number of vertices connected to the source vertex s
        """
        return self._count

    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.graphs.graph import Graph
    from algs4.stdlib.instream import InStream
    from 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("NOT connected")
    else: stdio.writeln("connected")
示例#15
0
        :raises ValueError:  unless 0 <= v < V
        """
        self._validateVertex(v)
        return self._adj[v].size()

    def __repr__(self):
        """
        Returns a string representation of this graph.
     
        :returns: the number of vertices V, followed by the number of edges E,
                    followed by the V adjacency lists
        """
        s = ["{} vertices, {} edges\n".format(self._V, self._E)]
        for v in range(self._V):
            s.append("%d : " % (v))
            for w in self._adj[v]:
                s.append("%d " % (w))
            s.append("\n")

        return ''.join(s)


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)
示例#16
0
                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()
示例#17
0
def _main():
    """
    For testing. The first command-line argument should be the name of
    the method that should be called. The optional second command-line
    argument should be the file or URL to read.
    """

    from algs4.stdlib import stdio

    testId = sys.argv[1]
    if len(sys.argv) > 2:
        inStream = InStream(sys.argv[2])
    else:
        inStream = InStream()

    if testId == 'readInt':
        stdio.writeln(inStream.readInt())
    elif testId == 'readAllInts':
        stdio.writeln(inStream.readAllInts())
    elif testId == 'readFloat':
        stdio.writeln(inStream.readFloat())
    elif testId == 'readAllFloats':
        stdio.writeln(inStream.readAllFloats())
    elif testId == 'readBool':
        stdio.writeln(inStream.readBool())
    elif testId == 'readAllBools':
        stdio.writeln(inStream.readAllBools())
    elif testId == 'readString':
        stdio.writeln(inStream.readString())
    elif testId == 'readAllStrings':
        stdio.writeln(inStream.readAllStrings())
    elif testId == 'readLine':
        stdio.writeln(inStream.readLine())
    elif testId == 'readAllLines':
        stdio.writeln(inStream.readAllLines())
    elif testId == 'readAll':
        stdio.writeln(inStream.readAll())
示例#18
0
def _regressionTest():
    """
    Perform regression testing.
    """

    clear()

    setPenRadius(.5)
    setPenColor(ORANGE)
    point(0.5, 0.5)
    show(0.0)

    setPenRadius(.25)
    setPenColor(BLUE)
    point(0.5, 0.5)
    show(0.0)

    setPenRadius(.02)
    setPenColor(RED)
    point(0.25, 0.25)
    show(0.0)

    setPenRadius(.01)
    setPenColor(GREEN)
    point(0.25, 0.25)
    show(0.0)

    setPenRadius(0)
    setPenColor(BLACK)
    point(0.25, 0.25)
    show(0.0)

    setPenRadius(.1)
    setPenColor(RED)
    point(0.75, 0.75)
    show(0.0)

    setPenRadius(0)
    setPenColor(CYAN)
    for i in range(0, 100):
        point(i / 512.0, .5)
        point(.5, i / 512.0)
    show(0.0)

    setPenRadius(0)
    setPenColor(MAGENTA)
    line(.1, .1, .3, .3)
    line(.1, .2, .3, .2)
    line(.2, .1, .2, .3)
    show(0.0)

    setPenRadius(.05)
    setPenColor(MAGENTA)
    line(.7, .5, .8, .9)
    show(0.0)

    setPenRadius(.01)
    setPenColor(YELLOW)
    circle(.75, .25, .2)
    show(0.0)

    setPenRadius(.01)
    setPenColor(YELLOW)
    filledCircle(.75, .25, .1)
    show(0.0)

    setPenRadius(.01)
    setPenColor(PINK)
    rectangle(.25, .75, .1, .2)
    show(0.0)

    setPenRadius(.01)
    setPenColor(PINK)
    filledRectangle(.25, .75, .05, .1)
    show(0.0)

    setPenRadius(.01)
    setPenColor(DARK_RED)
    square(.5, .5, .1)
    show(0.0)

    setPenRadius(.01)
    setPenColor(DARK_RED)
    filledSquare(.5, .5, .05)
    show(0.0)

    setPenRadius(.01)
    setPenColor(DARK_BLUE)
    polygon([.4, .5, .6], [.7, .8, .7])
    show(0.0)

    setPenRadius(.01)
    setPenColor(DARK_GREEN)
    setFontSize(24)
    text(.2, .4, 'hello, world')
    show(0.0)

    #import picture as p
    #pic = p.Picture('saveIcon.png')
    #picture(pic, .5, .85)
    #show(0.0)

    # Test handling of mouse and keyboard events.
    setPenColor(BLACK)
    from algs4.stdlib import stdio
    stdio.writeln('Left click with the mouse or type a key')
    while True:
        if mousePressed():
            filledCircle(mouseX(), mouseY(), .02)
        if hasNextKeyTyped():
            stdio.write(nextKeyTyped())
        show(0.0)

    # Never get here.
    show()