I a wrote a function SwapCities that is able to swap entries 3 and 4 in a list.
So f.e. [0,1,2,3,4] should become [0,1,2,4,3]. This function works perfectly, but strangely my original list also changes which I do not want.
This is my code:
def SwapCities(solution):
n = 3##randint(0,NumberOfCities-1)
m = 4##randint(0,NumberOfCities-1)
result = solution
temp1 = solution[n]
temp2 = solution[m]
result[n] = temp2
result[m] = temp1
return result
print "Start"
IncumbentSolution = list(x for x in range(0,NumberOfCities))
print IncumbentSolution
print "After swap" NewSolution = SwapCities(IncumbentSolution)
print NewSolution
print "Original solution"
print IncumbentSolution
I get the following result:
How many cities?
8 Start [0, 1, 2, 3, 4, 5, 6, 7]
After swap [0, 1, 2, 4, 3, 5, 6, 7]
Original solution [0, 1, 2, 4, 3, 5, 6, 7] (why did this change?!)
As you can see my original solution changed which it should not do.
I have no clue why this happens. Even when I change the code such that the changes to are applied to a copy of the original list I get this result. Could someone explain what I am doing wrong?
IncumbentSolution = list(x for x in range(0,NumberOfCities))
print "Start"
print IncumbentSolution
print "After swap"
tmpsolution = IncumbentSolution
NewSolution = SwapCities(tmpsolution)
print NewSolution
print "Original solution"
print IncumbentSolution
See Question&Answers more detail:
os