Search code examples
pythonfor-loopmultidimensional-arrayiterationnested-loops

My nested loop range is decreasing with every iteration


I have a nested for loop to iterate through my matrix where r and c are the rows and columns.

However, somehow with every iteration, c decreased.

e.g when r = 0, c will iterate from 0 to 9

when r = 1, c will iterate from 0 to 8

when r = 2, c will iterate from 0 to 7

i found this out by visualising the code on pythontutor

I tried putting some test values into the range e.g. 10 and it iterates perfectly for both c and r (aka it iterates from 0 to 9) so I have no idea what is the problem :(

my code is as seen below

def PDMap(r,c,sites):
    def distance2(x1,y1,x2,y2):
        return (x1-x2)**2 +(y1-y2)**2
    numberofsite= len(sites) 
    map1 = createZeroMatrix(r,c)
    for r in range(r):
        for c in range(c): #why is c decreasing??
            distancelist = []
            for i in range(len(sites)):
                distancelist.append(distance2(r,c,sites[i][0],sites[i][1]))
            if len(set(distancelist)) < 3:
                map1[r][c] = "X"
            else:
                map1[r][c]= distancelist.index(min(distancelist))
    return map1

Solution

  • It's because you have for c in range(c).

    The first iteration of the loop, the variable c gets overwritten. Try do something else, like for new_c in range(c).

    So your code should become:

    def PDMap(r,c,sites):
        def distance2(x1,y1,x2,y2):
            return (x1-x2)**2 +(y1-y2)**2
        numberofsite= len(sites) 
        map1 = createZeroMatrix(r,c)
        for r in range(r):
            for new_c in range(c): #why is c decreasing??
                distancelist = []
                for i in range(len(sites)):
                    distancelist.append(distance2(r,new_c,sites[i][0],sites[i][1]))
                if len(set(distancelist)) < 3: