add vertices to a non oriented graph using a list of lists

Viewed 31

In my code, I can only choose whether the graph is oriented, weighted, and the number of edges and I can't select the number of vertices.

Is there any way to add a parameter to my function control to select the number of vertices?

My code is below:

list_adj = []
list_w = []

def graph(list_adj,length,weight,oriented):
    count = 0
#non oriented
    if oriented == False:
        list_adj_non_o = [ [] for i in range(length) ]
        
        for i in range(length):
            k = random.randint(0,length-1)
            if k != i and k not in list_adj_non_o[i]:
                list_adj_non_o[i].append(k)
                if k != i and k not in list_adj_non_o[k]:
                    list_adj_non_o[k].append(i)
                    count +=1

                if weight == True:
                    list_w.append(random.randint(1,10))
                else:
                    list_w.append(1)
        
        print("list_adj_non_o : ",list_adj_non_o)
        print("list_w : ", list_w)
        print("number of vertices : ",count)

        return list_adj_non_o


graph(list_adj,10,False,False)

Thank you for helping me.

1 Answers

If you want more vertices, then add them. If you want them to be connected to existing vertices, you will have to add more edges. If you want less, remove some along with the edges that they are connected to.

As your graph generator is set up, you cannot independently set the number of edges and the number of vertices. If you want do this, you will have to change how you do the graph generation. Like this: create the vertices to the number of vertices specified. Select two vertices at random and add an edge between them. Repeat adding edges until you reach the specified number. Note that you may weel end up with vertices that are not connected.

Related