Exemple #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())
Exemple #2
0
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()
Exemple #3
0
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()
Exemple #4
0
def _main():
    """For testing:"""
    from itu.algs4.stdlib import stdio

    c1 = Color(128, 128, 128)
    stdio.writeln(c1)
    stdio.writeln(c1.getRed())
    stdio.writeln(c1.getGreen())
    stdio.writeln(c1.getBlue())
Exemple #5
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()
Exemple #6
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.")
Exemple #8
0
def _regressionTest():
    """Perform regression testing."""

    clear()

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

    setPenRadius(0.25)
    setPenColor(BLUE)
    point(0.5, 0.5)
    show(0.0)

    setPenRadius(0.02)
    setPenColor(RED)
    point(0.25, 0.25)
    show(0.0)

    setPenRadius(0.01)
    setPenColor(GREEN)
    point(0.25, 0.25)
    show(0.0)

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

    setPenRadius(0.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, 0.5)
        point(0.5, i / 512.0)
    show(0.0)

    setPenRadius(0)
    setPenColor(MAGENTA)
    line(0.1, 0.1, 0.3, 0.3)
    line(0.1, 0.2, 0.3, 0.2)
    line(0.2, 0.1, 0.2, 0.3)
    show(0.0)

    setPenRadius(0.05)
    setPenColor(MAGENTA)
    line(0.7, 0.5, 0.8, 0.9)
    show(0.0)

    setPenRadius(0.01)
    setPenColor(YELLOW)
    circle(0.75, 0.25, 0.2)
    show(0.0)

    setPenRadius(0.01)
    setPenColor(YELLOW)
    filledCircle(0.75, 0.25, 0.1)
    show(0.0)

    setPenRadius(0.01)
    setPenColor(PINK)
    rectangle(0.25, 0.75, 0.1, 0.2)
    show(0.0)

    setPenRadius(0.01)
    setPenColor(PINK)
    filledRectangle(0.25, 0.75, 0.05, 0.1)
    show(0.0)

    setPenRadius(0.01)
    setPenColor(DARK_RED)
    square(0.5, 0.5, 0.1)
    show(0.0)

    setPenRadius(0.01)
    setPenColor(DARK_RED)
    filledSquare(0.5, 0.5, 0.05)
    show(0.0)

    setPenRadius(0.01)
    setPenColor(DARK_BLUE)
    polygon([0.4, 0.5, 0.6], [0.7, 0.8, 0.7])
    show(0.0)

    setPenRadius(0.01)
    setPenColor(DARK_GREEN)
    setFontSize(24)
    text(0.2, 0.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 itu.algs4.stdlib import stdio

    stdio.writeln("Left click with the mouse or type a key")
    while True:
        if mousePressed():
            filledCircle(mouseX(), mouseY(), 0.02)
        if hasNextKeyTyped():
            stdio.write(nextKeyTyped())
        show(0.0)

    # Never get here.
    show()
        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")
Exemple #10
0
                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())
Exemple #11
0
        """
        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__":
    import sys

    from itu.algs4.stdlib import stdio
    from itu.algs4.stdlib.instream import InStream

    In = InStream(sys.argv[1])
    G = Graph.from_stream(In)
    stdio.writeln(G)
Exemple #12
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 itu.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())
Exemple #13
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)
Exemple #14
0
            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)
        :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 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("NOT connected")
    else: stdio.writeln("connected")
Exemple #16
0
def _main():
    """
    For testing.
    """
    import os
    import math
    from itu.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')
Exemple #17
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 itu.algs4.stdio.instream import InStream
    from itu.algs4.stdlib import stdio
    from itu.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))
        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__":
    import sys

    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)
    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")
Exemple #19
0
    fileName = f + ".wav"
    sound = pygame.mixer.Sound(fileName)
    samples = pygame.sndarray.samples(sound)
    temp = []
    for i in range(len(samples)):
        temp.append(float(samples[i]) / float(0x7FFF))
    return temp


# Initialize PyGame to handle audio.
try:
    pygame.mixer.init(_SAMPLES_PER_SECOND, _SAMPLE_SIZE, _CHANNEL_COUNT,
                      _AUDIO_BUFFER_SIZE)
    _channel = pygame.mixer.Channel(0)
except pygame.error:
    stdio.writeln("Could not initialize PyGame")
    sys.exit(1)

# -----------------------------------------------------------------------


def _createTextAudioFile():
    """For testing.

    Create a text audio file.

    """
    notes = [
        7,
        0.270,
        5,
Exemple #20
0
                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 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)
    finder = Cycle(G)
    if finder.has_cycle():
        for v in finder.cycle():
            stdio.writef("%i ", v)
        stdio.writeln()
    else:
        stdio.writeln("Graph is acyclic")
#!/usr/bin/env python3
from itu.algs4.sorting import merge
from itu.algs4.stdlib import stdio
"""
Reads a list of integers from standard input.
Then prints it in sorted order.
"""
L = stdio.readAllInts()

merge.sort(L)

if len(L) > 0:
    stdio.write(L[0])
for i in range(1, len(L)):
    stdio.write(" ")
    stdio.write(L[i])
stdio.writeln()
Exemple #22
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 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()