Esempio n. 1
0
def read_file(file):
    try:
        f = open(file, 'r')
    except exceptionGraph:
        raise exceptionGraph("The file is not available")
    firstLine = f.readline().strip().split()
    graph = Graph(0)
    number_of_vertices = int(firstLine[0])

    line = f.readline()
    while line != "":
        edge = line.strip().split()
        vertex1 = int(edge[0])
        vertex2 = int(edge[1])
        if vertex1 not in graph.parse_vertices():
            graph.add_vertex(vertex1)
        if vertex2 not in graph.parse_vertices() and vertex2 != -1:
            graph.add_vertex(vertex2)
        if len(edge) == 3 and vertex1 != vertex2 and not graph.is_edge(
                vertex1, vertex2):
            graph.add_edge(vertex1, vertex2, int(edge[2]))

        line = f.readline()

    if number_of_vertices != graph.get_nr_of_vertices():
        for vertex in range(number_of_vertices):
            if vertex not in graph.parse_vertices():
                graph.add_vertex(vertex)

    f.close()
    return graph
Esempio n. 2
0
def create_graph(initialGraph, validVertices):
    result_graph = Graph(0)
    for vertex in validVertices:
        result_graph.add_vertex(vertex)
    for vertex in validVertices:
        for neighbour in initialGraph.parse_neighbours(vertex):
            if not result_graph.is_edge(vertex, neighbour):
                result_graph.add_edge(vertex, neighbour,
                                      initialGraph.get_cost(vertex, neighbour))
    return result_graph
Esempio n. 3
0
def load_from_file(file):
    f = open(file, "r")

    line = f.readline().strip().split()
    vertices = int(line[0])
    edges = int(line[1])
    graph = Graph(vertices)
    for x in range(edges):
        line = f.readline().strip().split()
        x = int(line[0])
        y = int(line[1])
        z = int(line[2])
        graph.add_edge(x, y, z)
    return graph
Esempio n. 4
0
def random_graph(number_of_vertices, number_of_edges):
    minimum = input("Minimum cost: ")
    minimum = validate_vertex(minimum)
    maximum = input("Maximum cost: ")
    maximum = validate_vertex(maximum)

    if number_of_edges > number_of_vertices * number_of_vertices:
        raise exceptionGraph("The nr of edges must be < than nrVertices^2")

    graph = Graph(number_of_vertices)
    for vertex in range(number_of_edges):
        cost = random.randint(minimum, maximum)
        vertex1 = random.randrange(0, number_of_vertices)
        vertex2 = random.randrange(0, number_of_vertices)
        while graph.is_edge(vertex1, vertex2) or vertex1 == vertex2:
            vertex1 = random.randrange(0, number_of_vertices)
            vertex2 = random.randrange(0, number_of_vertices)
        graph.add_edge(vertex1, vertex2, cost)

    return graph