Exemplo n.º 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())
Exemplo n.º 2
0
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) == 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) == -1:
                print(key)
Exemplo n.º 3
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()))
Exemplo n.º 4
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()))
Exemplo n.º 5
0
        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))
Exemplo n.º 6
0
    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('{} {}')
Exemplo n.º 7
0
#!/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())
Exemplo n.º 8
0
from itu.algs4.sorting.insertion_sort import sort
from itu.algs4.stdlib.stdio import readString, readInt
import sys

m = readInt()
list = []

for i in range(m):
    n = readString()
    g = readString()
    list.append([g, n])
    # print("name: ", n,"grade: ", g)

list.sort()

for i in list:
    print(i[-1])
Exemplo n.º 9
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)
Exemplo n.º 10
0
#!/usr/bin/env python3
from itu.algs4.fundamentals.queue import Queue
from itu.algs4.stdlib import stdio

"""
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[str] = 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()))