首页 > 解决方案 > 当我尝试分配给一个列表时,为什么每个列表值都会改变?

问题描述

我正在尝试使用背包问题进行简单的爬山。

我有一个调整函数,旨在返回输入它的二进制值列表的稍微修改的值。然后我将这个新值与现有值进行比较,看看哪个更好。

但是,我遇到了这个奇怪的问题,当我尝试将新解决方案分配为当前解决方案的调整副本时,当前解决方案和新解决方案都立即被调整后的值替换。循环中的每个列表都被替换为相同的值,我不知道为什么。我已经对其他具有相同效果的列表进行了同样的尝试。为什么会这样?

编辑:从数组更改为列表

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

标签: python

解决方案


TempSolution = Solution[:] 这解决了问题!更多细节在评论中


推荐阅读