如何根据数独的条件删除字典值以删除错误的值?

时间:2019-02-21 01:35:41

标签: python numpy dictionary sudoku

我有一个解决数独功能,可以更新我的key = coordinates字典; value =可能的数字,取决于数独板上是否已经存在数字“ k”:

k = 8
for key, value in dic_i.items():
    if k in solving[key[0],0:]:
        if k in value:
            value.remove(k)
print(dic_i)

我在这里粘贴了部分解决的数独板和我的初始可能性字典:

solving = np.array([3, 1, 9, 4, 7, 2, 6, 8, 5],
                   [4, 5, 2, 6, 3, 8, 9, 7, 1],
                   [0, 0, 6, 9, 5, 1, 4, 2, 3],
                   [0, 0, 4, 1, 2, 0, *8, 5, 0],
                   [2, 6, 1, 5, 8, 9, 3, 4, 7],
                   [0, 3, 5, 7, 4, 0, 0, 0, 0],
                   [5, 4, 3, 8, 1, 7, 2, 0, 0],
                   [6, 2, 7, 3, 9, 4, 5, 1, 8],
                   [1, 9, 8, 2, 6, 5, 7, 3, 4]])
dic_i
Out[1081]: 
{(2, 0): [7, 8],
 (2, 1): [7, 8],
 (3, 0): [7, 8, 9],
 (3, 1): [7, 8],
 (3, 5): [3, 6, 9],
 (3, 8): [6, 9],
 (5, 0): [8, 9],
 (5, 5): [6, 9],
 (5, 6): [1, 8],
 (5, 7): [6, 9],
 (5, 8): [2, 6, 9],
 (6, 7): [6, 9],
 (6, 8): [6, 9]}

我专注于从第4行中删除可能的数字“ 8”,在顶部运行代码后,我得到:

dic_i
Out[1080]: 
{(2, 0): [7, 8],
 (2, 1): [7],
 (3, 0): [7, 9],
 (3, 1): [7],
 (3, 5): [3, 6, 9],
 (3, 8): [6, 9],
 (5, 0): [8, 9],
 (5, 5): [6, 9],
 (5, 6): [1, 8],
 (5, 7): [6, 9],
 (5, 8): [2, 6, 9],
 (6, 7): [6, 9],
 (6, 8): [6, 9]}

我似乎无法弄清楚(2,1)-数字8被删除了吗???第3行中没有数字8 ...(对于(3,0)和(3,1),它正确删除了数字8)。

1 个答案:

答案 0 :(得分:-1)

当我运行它时它会起作用。

import numpy as np
solving = np.array([[3, 1, 9, 4, 7, 2, 6, 8, 5],
                   [4, 5, 2, 6, 3, 8, 9, 7, 1],
                   [0, 0, 6, 9, 5, 1, 4, 2, 3],
                   [0, 0, 4, 1, 2, 0, 8, 5, 0],
                   [2, 6, 1, 5, 8, 9, 3, 4, 7],
                   [0, 3, 5, 7, 4, 0, 0, 0, 0],
                   [5, 4, 3, 8, 1, 7, 2, 0, 0],
                   [6, 2, 7, 3, 9, 4, 5, 1, 8],
                   [1, 9, 8, 2, 6, 5, 7, 3, 4]])

dic_i = {(2, 0): [7, 8],
 (2, 1): [7, 8],
 (3, 0): [7, 8, 9],
 (3, 1): [7, 8],
 (3, 5): [3, 6, 9],
 (3, 8): [6, 9],
 (5, 0): [8, 9],
 (5, 5): [6, 9],
 (5, 6): [1, 8],
 (5, 7): [6, 9],
 (5, 8): [2, 6, 9],
 (6, 7): [6, 9],
 (6, 8): [6, 9]}

k = 8
for key, value in dic_i.items():
    if k in solving[key[0],0:]:
        if k in value:
            value.remove(k)
print(dic_i)

打印:

{(2, 0): [7, 8],
(2, 1): [7, 8],
(3, 0): [7, 9],
(3, 1): [7],
(3, 5): [3, 6, 9],
(3, 8): [6, 9],
(5, 0): [8, 9],
(5, 5): [6, 9],
(5, 6): [1, 8],
(5, 7): [6, 9],
(5, 8): [2, 6, 9],
(6, 7): [6, 9],
(6, 8): [6, 9]}