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)

我的目标是打印一张如下的地图:
9 8 7 6 5 4 3 2 1
8 7 6 5 4 3 2 1 9
7 6 5 4 3 2 1 9 8
6 5 4 3 2 1 9 8 7
5 4 3 2 1 9 8 7 6
4 3 2 1 9 8 7 6 5
3 2 1 9 8 7 6 5 4
2 1 9 8 7 6 5 4 3
1 9 8 7 6 5 4 3 2
但我不明白为什么它只是打印:
9 8 8 8 8 8 8 8 8 8
8 9 9 9 9 9 9 9 9 9 9
8 9 9 9 9 9 9 9 9 9 9
8 9 9 9 9 9 9 9 9 9 9
8 9 9 9 9 9 9 9 9 9 9
8 9 9 9 9 9 9 9 9 9 9
8 9 9 9 9 9 9 9 9 9 9
8 9 9 9 9 9 9 9 9 9 9
8 9 9 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/

10-12 05:30