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.")
示例#2
0
if len(sys.argv) > 1:
    try:
        sys.stdin = open(sys.argv[1])
    except IOError:
        print("File not found")

K = 20
D = 10000
keys = []
sequences = []

# reading the data
sequence = ""
finalSequence = ""
while not stdio.isEmpty():
    line = stdio.readLine()
    if (line.startswith('>')):
        firstLine = line.split(" ")
        name = firstLine[0][1:]
        keys.append(name)
        sequence = ""
        finalSequence = ""
    else:
        sequence = sequence + line
        if (len(sequence) > 2): finalSequence = sequence
    if (finalSequence != ""):
        sequences.append(finalSequence)

# checking if the file was read correctly
for i in range(0, len(keys)):
    print(keys[i], " >", sequences[i], " length: ", len(sequences[i]))
示例#3
0
        """
        self._validateVertex(v)
        return self._keys[v]

    def digraph(self):
        return self._graph

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


if __name__ == "__main__":
    import sys

    filename = sys.argv[1]
    delimiter = sys.argv[2]
    sg = SymbolDigraph(filename, delimiter)
    graph = sg.digraph()
    while stdio.hasNextLine():
        source = stdio.readLine()
        if sg.contains(source):
            s = sg.index_of(source)
            for v in graph.adj(s):
                stdio.writef("\t%s\n", sg.name_of(v))
        else:
            stdio.writef("input not contain '%i'", source)
示例#4
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
示例#5
0
if len(sys.argv) > 1:
    try:
        sys.stdin = open(sys.argv[1])
    except IOError:
        print("File not found, using standard input instead")

startTime = time.time()
States = []

numberOfStates = int(sys.stdin.readline())
numberOfSeats = int(sys.stdin.readline())
#print ("number Of States: ", numberOfStates, ", number Of Seats: ", numberOfSeats )

while not stdio.isEmpty():
    name = stdio.readLine()
    population = stdio.readLine()
    States.append(State(name, population))

statesCopy = sorted(list(States))

remainingSeats = numberOfSeats - numberOfStates

while remainingSeats > 0:
    statesCopy[0].increaseSeats()
    remainingSeats -= 1

    toInsert = statesCopy[0]
    del statesCopy[0]

    bisect.insort(statesCopy, toInsert)
示例#6
0
    file = open(filename, 'r')
    st = {}
    ts = {}

    line = file.readline()
    while line:
        fields = line.split(separator)
        key = fields[0]
        for i in range(1, len(fields)):
            val = fields[i]
            if not key in st:
                st[key] = Queue()
            if not val in ts:
                ts[val] = Queue()
            st.get(key).enqueue(val)
            ts.get(val).enqueue(key)
        line = file.readline()
    print("Done indexing")

    #read queries from standard input, one per line
    while not stdio.isEmpty():
        query = stdio.readLine()
        if query in st:
            for vals in st.get(query):
                print("  " + vals)
        if query in ts:
            for keys in ts.get(query):
                print("  " + keys)

    file.close()