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():
    """
    Reads strings from stdin and adds them to a minimum priority queue.
    When reading a '-' it removes the minimum element and prints it to stdout.
    """
    pq = MinPQ()
    while not stdio.isEmpty():
        item = stdio.readString()
        if item != '-':
            pq.insert(item)
        elif not pq.is_empty():
            print(pq.del_min())
    print("({} left on pq)".format(pq.size()))
def main():
    """
    Reads strings from first input file and sorts them
    Reads strings from second input file and prints every string not in first input file
    """
    if len(sys.argv) is 3:
        sys.stdin = open(sys.argv[1])
        arr = stdio.readAllStrings()
        arr.sort()
        sys.stdin = open(sys.argv[2])
        while not stdio.isEmpty():
            key = stdio.readString()
            if index_of(arr, key) is -1:
                print(key)
def main():
    """
    Reads strings from stdin, adds them to a red-black BST with values 0..n,
    prints all key value pairs to stdout.
    """
    st = RedBlackBST()
    i = 0
    while not stdio.isEmpty():
        key = stdio.readString()
        st.put(key, i)
        i += 1
    for s in st.keys():
        print("{} {}".format(s, st.get(s)))
    print()
Exemple #5
0
def main():
    """
    Reads strings from stdin and adds them to a priority queue.
    When reading a '-' it removes a maximum item on the priority queue and prints it to stdout.
    Prints the amount of items left on the priority queue
    """
    pq = MaxPQ()
    while not stdio.isEmpty():
        item = stdio.readString()
        if item != '-':
            pq.insert(item)
        elif not pq.is_empty():
            print(pq.del_max())
    print("({} left on pq)".format(pq.size()))
Exemple #6
0
def main():
    """
    Reads strings from an stdin and adds them to a queue.
    When reading a '-' it removes the least recently added item and prints it.
    Prints the amount of items left on the queue.
    """
    queue = Queue()
    while not stdio.isEmpty():
        input_item = stdio.readString()
        if input_item != '-':
            queue.enqueue(input_item)
        elif not queue.is_empty():
            print(queue.dequeue())
    print('({} left on queue)'.format(queue.size()))
Exemple #7
0
"""
 *  The {@code FileIndex} class provides a client for indexing a set of files,
 *  specified as command-line arguments. It takes queries from standard input
 *  and prints each file that contains the given query.
"""

# key = word, value = set of files containing that word
if __name__ == '__main__':
    st = {}
    args = sys.argv[1:]

    # create inverted index of all files
    print("Indexing files")
    for filename in args:
        print("  " + filename)
        file = open(filename, 'r')
        for line in file.readlines():
            for word in line.split():
                if not word in st:
                    st[word] = set()
                s = st.get(word)
                s.add(file)

    # read queries from standard input, one per line
    while not stdio.isEmpty():
        query = stdio.readString()
        if query in st:
            s = st.get(query)
            for file in s:
                print(" " + file.name)
Exemple #8
0
  standard input and prints out a word (whose length exceeds
  the threshold) that occurs most frequently to standard output.
  It also prints out the number of words whose length exceeds
  the threshold and the number of distinct such words.
"""

if __name__ == '__main__':
    args = sys.argv[1:]
    distinct = 0
    words = 0
    minlen = int(args[0])
    st = {}

    #compute frequency counts
    while not stdio.isEmpty():
        key = stdio.readString()
        if len(key) < minlen:
            continue
        words += 1
        if key in st:
            st[key] = st.get(key) + 1
        else:
            st[key] = 1
            distinct += 1

    # find a key with the highest frequency count
    max = ""
    st[max] = 0
    for word in st.keys():
        if st.get(word) > st.get(max):
            max = word
Exemple #9
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)
Exemple #10
0
    where V is the number of currencies.

    For additional documentation, see Section 4.4 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
    """
    if len(sys.argv) > 1:
        try:
            sys.stdin = open(sys.argv[1])
        except IOError:
            print("File not found, using standard input instead")

    # V currencies
    V = stdio.readInt()
    name = [None] * V

    # Create complete network
    graph = EdgeWeightedDigraph(V)
    for v in range(V):
        name[v] = stdio.readString()
        for w in range(V):
            rate = stdio.readFloat()
            edge = DirectedEdge(v, w, -math.log(rate))
            graph.add_edge(edge)

    # find negative cycle
    spt = BellmanFordSP(graph, 0)
    if spt.has_negative_cycle():
        stake = 1000.0
        for edge in spt.negative_cycle():
            print('{} {}', stake, name[edge.from_vertex()])
            stake *= math.exp(-edge.weight())
            print('{} {}')