为什么我的 Lifo Queue 中的项目会在不参考它们的情况下发生变化?

问题描述

我正在处理图形着色问题,我有一个每个节点可以采用的可能颜色值 (0,1,2,3) 的字典。我在这里尝试一些蛮力方法只是为了了解算法。我遇到了一个我无法纠正的简单问题。基本上,每当我选择颜色时,我都需要跟踪每本字典,因此如果它最终不起作用,我可以回溯到那个点。下面是输出出错的地方。我已经插入了所有这些打印语句来尝试诊断问题。我将节点 9 设置为颜色 2,并将替代选择排队,以防我不得不回溯到此选择。

设置 9 等于 2

排队 9 的替代选择(以下是添加到 LifoQueue 的替代选择,这是关键

 {0: [0],1: [0],2: [1],3: [2],4: [1],5: [0],6: [2],7: [1],8: [0],9: [3],10: [2,3],11: 
  [3],12: [0,13: [1,14: [0,15: [0,16: [0,17: [0,18: [2,19: 
  [1,3]}

然后代码使用选择来根据预定义的边从其他节点中消除可能的颜色,节点 9 设置为 2

边缘 9 到 10

 {0: [0],9: [2],10: [3],11: [3],19: [1,3]}

边缘 9 到 12

 {0: [0],3]}

将 10 设置为 3(这里没有替代队列,因为节点 10 只有一个选项)

边缘 10 到 11

 {0: [0],11: [],3]}

在这里你可以看到节点 11 的选项现在是空白的,这告诉我——充其量——我做的最后一个选择是错误的,所以这会触发回溯到放入队列的最后一个项目,这,如前所述,是节点 9 值为 3 的字典。问题是,当我在这里执行 q.get() 时,这是我得到的输出(与我添加到上面的队列的内容进行比较:

 {0: [0],3]}

在我不接触队列的情况下,队列条目如何更改?下面是相关代码。

'''

# edges are the constraint store (?)
edges = [some pre-defined list of tuples defining the edges]

# building a solution template
solution = [0]*node_count

# global constraint of four colors 
colors = [0,3]

# dictionary covering possible colors for each node
sols = {node:colors.copy() for node in range(0,node_count)}

#initiating a queue to store checkpoints for backtracking
q = queue.LifoQueue()


#placing the first entry in the queue
q.put((0,sols))

place = 0
while place < node_count:
    backtracked = False
    cursor = q.get()
    print('cursor is ',cursor)
    place = cursor[0]
    dic = cursor[1]
    val = dic[place][0]

    #any time a value is chosen from multiple,it needs to be queued
    if len(dic[place]) > 1:
        dic_copy = dic.copy()
        dic_copy[place].remove(val)
        q.put((place,dic_copy))
        
    #choosing a value
    solution[place] = val
    dic[place] = [solution[place]]
    
    print('Setting ',place,'equal to ',val)
    for edge in edges:
        if backtracked == False:
            if edge[0] == place:                
                if solution[place] in dic[edge[1]]:
                    #in case of failure,store copy
                    vals = dic[edge[1]].copy()
                    dic[edge[1]].remove(solution[place])
                    if len(dic[edge[1]]) == 0:
                        backtracked = True
                            
    if backtracked == False:
        q.put((place+1,dic))
    else:
        print('backtracking')

'''

解决方法

使用 deepcopy 而不是我使用的常规副本解决了这个问题。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...