Home > Mobile >  Out of range in a list inside a list
Out of range in a list inside a list

Time:10-14

I have a "out of range" probem. This is the code:

S = []
while( len(edges) != 0):
   e = random.randint(0,len(edges)-1)
   k = random.randint(0,1)
   Vert = edges[e][k]
   print(Vert)
   S.append(Vert)           

   for i in range(len(edges)):
       for j in range(2):
           if edges[i][j] == Vert:
              edges.pop([i][0])
if edges[i][j] == Vert:



IndexError: list index out of range

edges is an list like following:

[(0, 2), (0, 3), (0, 4), (1, 2), (2, 3), (2, 4), (3, 4)]

Any ideia how to fix?

I have also tried the "in" sytanx like

S = []  # Dominating Set

while( len(edges) != 0):
    e = random.randint(0,len(edges)-1)
    k = random.randint(0,1)
    Vert = edges[e][k]
    print(Vert)
    S.append(Vert)           

    for i in range(len(edges)):
 
            if Vert in edges[i]:
                edges.pop([i]) 

But get the error

TypeError: 'list' object cannot be interpreted as an integer

The ideia of the code is find the dominating set in a graph and the algorithm goes as follow

#    First we have to initialize a set ‘S’ as empty
#    Take any edge ‘e’ of the graph connecting the vertices ( say A and B )
#    Add one vertex between A and B ( let say A ) to our set S
#    Delete all the edges in the graph connected to A
#    Go back to step 2 and repeat, if some edge is still left in the graph
#    The final set S is a Dominant Set of the graph

After some thinking I did another verison but still got the out of range error:

    size = len(edges)
    i = 0
    while( size != i):
        for j in range(2):
            if edges[i][j] == Vert:
                edges.pop([i][0])
                size = size-1
                i = 0
            else:
                i = i 1

CodePudding user response:

What you're doing in the operation of edges.pop([i][j]) is actually you're creating a new list [i], and then trying to access element [j] of that one-length list.

CodePudding user response:

for i in range(len(edges)):
    for j in range(2):
        if edges[i][j] == Vert:
            edges.pop([i][j])

When you call edges.pop(), that makes the list smaller, and the outer for loop for i in range(len(edges)) will try to iterate over an element that isn't there anymore.

  • Related