Ejemplo 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())
Ejemplo n.º 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()))
Ejemplo n.º 3
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) 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)
Ejemplo n.º 4
0
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()
Ejemplo n.º 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()))
Ejemplo n.º 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()))
Ejemplo n.º 7
0
    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.")
Ejemplo n.º 8
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)
Ejemplo n.º 9
0
from algs4.stdlib import stdio
from priority_queue import MaxPQ, Node
import math
import sys

pq = MaxPQ()

states = stdio.readInt()                                            # assign the amount of states
total_seats = stdio.readInt()                                       # assign the amount of seats
allocated_seats = states
remaining_seats = total_seats -allocated_seats
 

while not stdio.isEmpty():                                          # make sure our file still has values 
    
    state = str(stdio.readLine()).strip('\n')                       # assign statename and population count 
    population = int(stdio.readLine())
    priority = population / math.sqrt(1*(1+1))
    
    initial_seat = 1                                                # initialize 1 seat per state
    current_node = Node(state, priority, population, initial_seat)
    pq.insert(current_node)
    

while allocated_seats < total_seats:                                # run untill we have no more seats  
    item = pq.del_max()                                             # extract highest prioritized item in the queue
    s = item.seats
    p = item.population
    item.seats += 1
    allocated_seats += 1
    constant = math.sqrt(item.seats*(item.seats+1))                 # calculate constant that is used for division
Ejemplo n.º 10
0
        try:
            sys.stdin = open(sys.argv[1])
        except IOError:
            print("File not found, using standard input instead")
    start_time = time.time()
    n = stdio.readInt()
    qf = MyUnionFind(n)

    step = 0
    isolated = n
    connectedStep = 0
    giantComponentStep = 0
    isolatedStep = 0
    connected = 0

    while not stdio.isEmpty() and connected == 0:
        #for i in range(n): print(qf._id[i], end=" ")
        #print("")
        step += 1
        p = stdio.readInt()
        q = stdio.readInt()
        if qf.connected(p, q):
            continue
        qf.union(p, q)

        if qf.count() == 1 and connected == 0:
            connectedStep = step
            connected = 1

        max = qf._biggestComponent
        if max > round(n / 2) and giantComponentStep == 0: