python - 数独与 python

标签 python algorithm sudoku

def print_map(sudoku_map):
    for line in sudoku_map:
        print(line)
        print("\n") 

#it will determine whether there is a same a in row or not
def search_row(sudoku_map_search, a, row):
    for i in range(9):
        if sudoku_map_search[row][i] == a:
            return 0;
        else:
            return 1;

#it will determine whether there is a same a in column or not
def search_column(sudoku_map_search, a, column):
    for b in range(9):
        if sudoku_map_search[b][column] == a:
            return 0;
        else:
            return 1;

sudoku_map = [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],

[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],

[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
];

for row in range(9):
    for column in range(9):
        #if block is empty loop will place a number;
        if sudoku_map[row][column]==0:
            #a will be a number which will try all the numbers between 0-10 for blank places
            for a in range(1,10):
                if search_row(sudoku_map, a ,row)==1 and search_column(sudoku_map, a, column)==1:
                    sudoku_map[row][column]= a

print_map(sudoku_map)

我的目标是打印一张如下所示的 map :

  1. 9 8 7 6 5 4 3 2 1
  2. 8 7 6 5 4 3 2 1 9
  3. 7 6 5 4 3 2 1 9 8
  4. 6 5 4 3 2 1 9 8 7
  5. 5 4 3 2 1 9 8 7 6
  6. 4 3 2 1 9 8 7 6 5
  7. 3 2 1 9 8 7 6 5 4
  8. 2 1 9 8 7 6 5 4 3
  9. 1 9 8 7 6 5 4 3 2

但我不明白为什么它只是打印:

  1. 9 8 8 8 8 8 8 8 8
  2. 8 9 9 9 9 9 9 9 9
  3. 8 9 9 9 9 9 9 9 9
  4. 8 9 9 9 9 9 9 9 9
  5. 8 9 9 9 9 9 9 9 9
  6. 8 9 9 9 9 9 9 9 9
  7. 8 9 9 9 9 9 9 9 9
  8. 8 9 9 9 9 9 9 9 9
  9. 8 9 9 9 9 9 9 9 9

你知道为什么我无法实现我的目标吗?

最佳答案

在搜索函数中使用 else 和 for 循环。这样,仅当没有迭代返回中断时才返回 1。您甚至可以在 for 循环后简单地返回 1。

#it will determine whether there is a same a in row or not
def search_row(sudoku_map_search, a, row):
    for i in range(9):
        if sudoku_map_search[row][i] == a:
            return 0;
    else:
        return 1;

或者在 for 循环后返回 1。仅当没有迭代成功时才会返回 1。

#it will determine whether there is a same a in row or not
def search_row(sudoku_map_search, a, row):
    for i in range(9):
        if sudoku_map_search[row][i] == a:
            return 0;
    return 1;

关于python - 数独与 python ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34458596/

相关文章:

algorithm - 我如何深入比较 2 个 Lua 表,它们可能有也可能没有表作为键?

java - 尝试以数独样式打印二维数组

python - 编写一个将装饰器应用于所有方法的类装饰器

python - 如何在 Ubuntu 中使用 numpy 和 OpenBLAS 而不是 Atlas?

javascript - 将 python 中的嵌套排序循环转换为 javascript

java - 倒置计数(大输入问题)

c++ - 计数倒置归并排序算法中的移位

java - 在 DocumentListener 中访问 JTextField

Java 数独生成器无法正常工作

python - 如何在 IPython 中自动设置默认路径