python数独游戏
我的目标是打印一张地图,看起来像:python数独游戏,python,algorithm,sudoku,Python,Algorithm,Sudoku,我的目标是打印一张地图,看起来像: 9876542 1 876543219 7654232198 654321987 5 4 3 2 1 9 8 7 6 432198765 3 2 1 9 8 7 6 5 4 219876543 1987655432 但我不明白为什么它只是打印: 988888 8999999 8999999 8999999 8999999 8999999 8999999 8999999 8999999 你知道我为什么不能达到目标吗?在搜索函数中使用else和for循环。这样,只
你知道我为什么不能达到目标吗?在搜索函数中使用else和for循环。这样,只有在没有迭代返回中断时才返回1。您甚至可以在for循环之后简单地返回1
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)
或者在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;
else:
return 1;
可以使用生成器表达式,使用该表达式将返回1或0,即True或False。您的代码看起来像是在尝试编写c而不是python,在python中,您可以在列表元素上迭代,而无需索引,并且不需要分号
您的功能可以简化为:
#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;
any
延迟评估任何ele==a
上的短路是否为真,如果未找到匹配项,则只会返回False
要检查是否存在匹配项,您只需执行以下操作:
def search_row(sudoku_map_search, a, row):
return any(ele == a for ele in sudoku_map_search[row])
您不需要使用=
显式检查返回值
您还可以使用str.join
简化打印功能:
if search_row(sudoku_map, a ,row):
sudoku_map[row][column] = a
或使用打印功能:
def print_map(sudoku_map):
print("\n".join(sudoku_map))
是的,这对我有帮助。现在我可以继续思考我的算法了。非常感谢。
# needed for python2
from __future__ import print_function
def print_map(sudoku_map):
print(*sudoku_map, sep="\n")