我在Python的帮助下创建了一个基本的数独检查程序。 但是,结果始终显示为“False”。 代码如下:
list = [[1,2,3,4],
[2,4,1,3],
[3,1,4,2],
[4,3,2,1]]
def sudoku_check(list):
n = len(list)
digit = 1
while digit <= n:
row_count = 0
col_count = 0
v = 0
while v < n:
x = 0
while x < n:
print ("Check")
if digit == list[v][x]:
row_count = row_count + 1
if digit == list[x][v]:
col_count = col_count + 1
x = x + 1
v = v + 1
if col_count != 1 or row_count != 1:
return False
digit = digit + 1
return True
print (sudoku_check(list))
我是编程新手。非常感谢您的帮助。 感谢
答案 0 :(得分:1)
好的,为您提供解决方案/可以解释您的问题@ShreyashKarnik!
代码中的问题来自下面的块:
while digit <= n:
row_count = 0
col_count = 0
v = 0
while v < n:
x = 0
while x < n:
print ("Check")
if digit == sudo_board[v][x]:
row_count = row_count + 1
if digit == sudo_board[x][v]:
col_count = col_count + 1
x = x + 1
v = v + 1
if col_count != 1 or row_count != 1:
return False
那么这段代码究竟在做什么?它会遍历你的数独板中的每个单元格并寻找一个数字。为了便于解释,我们假设它正在寻找数字1
。它检查整个电路板中的每个单元,并且由于1
总共出现4次,col_count
和row_count
每次都会4
。如果您愿意,可以使用print语句进行验证!
由于您的错误检查是针对号码1
进行检查,因此每次都会失败。所以,让我们开始寻找解决方案!
"Pythonic means code that doesn't just get the syntax right but that follows the conventions of the Python community"
。你说你是编程的新手,所以学习如何编写python的正确方式很重要。您在上面的代码中遇到了几个问题:
让我们从最后的评论开始,缺乏模块化,并在此过程中解决其他问题。确定数独网格是否有效实际上非常复杂 - 它有三个组成部分。 1.所有行都有正确的位数吗? 2.所有列都有正确的位数吗? 3.网格作为一个整体是否具有正确的位数?
3实际上是1和2的因子,你在代码中想到了 - 很好!但如果我们将第一和第二部分内容分解为自己的功能,它可能会使事情变得更容易阅读。那些看起来怎么样?让我们先做行。对于我们的功能,我们将检查每一行并确认它具有正确的位数。
让我们从行检查器开始。我们所要做的就是:
def has_correct_number_rows(sudo_board):
# the set we create below is an unordered grouping of the numbers
# 1-4.
correct_set = set(range(1, len(sudo_board)))
for row in sudo_board:
# this if statement checks if our row contains values 1-4
if (correct_set != set(row)):
return False
return True
如果所有行都包含正确的项目数,则返回True,否则将返回false。
接下来,检查正确的列数。这稍微复杂一些,但仍然相当简单:
def has_correct_number_cols(sudo_board):
correct_set = set(range(1, len(sudo_board) + 1))
for col_num in range(0, len(sudo_board)):
# col_set creates a set of the elements in a given column
col_set = set([row[col_num] for row in sudo_board])
if (correct_set != set(row)):
return False
return True
此处的返回值相同。
既然您拥有这两个功能,那么您的最终检查实际上非常简单。它在下面:
def sudoku_check_peter(sudo_board):
correct_rows = has_correct_number_rows(sudo_board)
correct_cols = has_correct_number_cols(sudo_board)
# This last line returns True if both are true, otherwise
# False.
return correct_rows and correct_cols
这最终变得非常罗嗦,我为此道歉 - 乐于回答后续问题或解释更多内容!希望这有帮助。