Esempio n. 1
0
def bipartite(V1, V2, E):
    '''
     * Returns a random simple bipartite graph on V1 and V2 vertices
     * with E edges.
     * @param V1 the number of vertices in one partition
     * @param V2 the number of vertices in the other partition
     * @param E the number of edges
     * @return a random simple bipartite graph on V1 and V2 vertices,
     *    containing a total of E edges
     * @raises ValueError if no such simple bipartite graph exists
    '''
    if E > V1 * V2:
        raise ValueError('Too many edges')
    if E < 0:
        raise ValueError('Too few edges')
    # Modification question #5
    if V1 < 0 or V2 < 0:
        raise ValueError("Vertex value cannot be less then 0")
    G = Graph(V1 + V2)
    vertices = [i for i in range(V1 + V2)]
    rand.shuffle(vertices)
    edges = []
    while G.E() < E:
        i = rand.randrange(V1)
        j = V1 + rand.randrange(V2)
        e = (vertices[i], vertices[j])
        if e not in edges:
            edges.append(e)
            G.add_edge(e)
    return G
Esempio n. 2
0
def simple(V, E):
    '''
    Returns a random simple graph containing V vertices and E edges.
    @param V the number of vertices
    @param E the number of edges
    @return a random simple graph on V vertices, containing a total of E edges
    @raises ValueError if no such simple graph exists
    '''
    if E > V * (V - 1) / 2:
        raise ValueError("Too many edges")
    if E < 0:
        raise ValueError("Too few edges")
    # Modification question #5
    if V <= 0:
        raise ValueError("A simple graph must have at least one vertex")
    G = Graph(V)
    edges = []
    while G.E() < E:
        v = rand.randrange(V)
        w = rand.randrange(V)
        e = (v, w)
        if v != w and e not in edges:
            edges.append(e)
            G.add_edge(e)
    return G