I am trying to do a simple hill climb using a knapsack problem.
I have a tweak function that's meant to return a slightly modified value of the list of binary values fed into it. I then compare this new value with the existing one to see what's better.
However, I have come across this odd issue where both current solution and new solution is being replaced with the tweaked values immediately when I try to assign the new solution as a tweaked copy of the current solution. Every list in the loop is being replaced with the same values, and I have no idea why. I have tried the same thing with other lists with the same effect. Why is this happening?
Edit: Changed from array to list
from random import randrange
import numpy as np
val = [8, 7, 6, 3, 3]
iteration = 0
def generateInitialState():
array = []
k=0
while k != len(val):
array.append(randrange(0,2))
k+=1
return array
CurrentSolution = generateInitialState()
def Quality(Solution):
sum_items = 0
newValue = np.multiply(val,Solution)
for item in newValue:
sum_items += item
return sum_items
def Tweak(Solution):
print(str(Solution) + ' : ' + str(Quality(Solution)))
TempSolution = Solution
if Solution[iteration] is 0:
TempSolution[iteration] = 1
else:
TempSolution[iteration] = 0
print(str(TempSolution) + ' : ' + str(Quality(TempSolution)))
return TempSolution
while iteration < 5:
iteration+=1
NewSolution = Tweak(CurrentSolution)
if Quality(NewSolution) > Quality(CurrentSolution):
print('New good value detected'+ str(Quality(NewSolution)))
CurrentSolution = NewSolution
else:
print('Best solution found')
break