0

I have a function which basically uses the dijkstra's algorithm to find distances in a graph

def getDistances(q,start):

print(q)

q[start][0] = 0
queue = [start]
while len(queue):


    m = []


    mMin = queue[0]
    m = q[mMin][2]
    queue.remove(mMin)


    for x in q[m][3]:

        if q[x][1] == 0:

            if not x in queue:
                queue.append(x)

            if q[x][0] > q[m][0] + 1:

                q[x][0] = q[m][0] + 1

    q[m][1] = 1

return [x[0] for x in q]

But it works perfectly. However, I have to call this function several times. and the "q" argument stays the same. Here's the invocation:

for ex in exits:
    dist = getDistances(list(qt),ex)
    distances.append([ex,dist])

"qt" itself is a list which contains a lot of different parameters. In this case I consider it not as important as the problem itself.

The problem "qt" variable is modified if the "q" variable is modified inside the function. As you can see in invocation, i have tried to use list(qt) to pass the variable by value not by reference. Thanks for any help in advance!

tna0y
  • 1,842
  • 3
  • 16
  • 33

2 Answers2

2

You have to create a deepcopy:

from copy import deepcopy

dist = getDistances(deepcopy(qt), ex)
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0

You need to copy the elements in the list too. As for example: q[x][0] = q[m][0] + 1 modifies them. Do:

dist = getDistances(list(list(e) for e in qt), ex)
Dan D.
  • 73,243
  • 15
  • 104
  • 123