0

i am facing the weirdest issue in the python.In the following code i am never changing the variable best_solution in the for loop but if you check the print output best_solution variable is changing in every loop. please help

    import random

class simulated_anneling():
    def __init__(self,initial_temprature,alpha) -> None:
        pass
    
    def neighbour_solution(self,solution):
        
        A=random.randint(0,len(solution)-1)
        B=random.randint(0,len(solution)-1)
        while A==B:
            B=random.randint(0,len(solution)-1)
        temp=solution[A]
        solution[A]=solution[B]
        solution[B]=temp
        return solution
    


solution=list(range(3))
best_solution=solution
SA=simulated_anneling(1,9)
for i in range(10):
    print("best solution at sta of ",i,"=>",best_solution)
    new_solution=SA.neighbour_solution(solution)
    print("best solution at end of ",i,"=>",best_solution)

output of the code is as follows

best solution at sta of  0 => [0, 1, 2]
best solution at end of  0 => [1, 0, 2]
best solution at sta of  1 => [1, 0, 2]
best solution at end of  1 => [1, 2, 0]
best solution at sta of  2 => [1, 2, 0]
best solution at end of  2 => [0, 2, 1]
best solution at sta of  3 => [0, 2, 1]
best solution at end of  3 => [0, 1, 2]
best solution at sta of  4 => [0, 1, 2]
best solution at end of  4 => [1, 0, 2]
best solution at sta of  5 => [1, 0, 2]
best solution at end of  5 => [1, 2, 0]
best solution at sta of  6 => [1, 2, 0]
best solution at end of  6 => [2, 1, 0]
best solution at sta of  7 => [2, 1, 0]
best solution at end of  7 => [1, 2, 0]
best solution at sta of  8 => [1, 2, 0]
best solution at end of  8 => [2, 1, 0]
best solution at sta of  9 => [2, 1, 0]
best solution at end of  9 => [1, 2, 0]
RISHIIII
  • 1
  • 2
  • `best_solution=solution` makes those two names point to the same list, so if you change `solution`, it will also change `best_solution`, since they're the same list. You need to make a copy before assigning to prevent that. – Carcigenicate Feb 24 '23 at 00:11

0 Answers0