我需要检查用户插入的数字是否已经在列、行或“ block ”中(仍在处理最后一部分)。
出于某种原因,这些检查不起作用,我不明白为什么?
我在 shell 中编写了相同的代码,它工作得很好。
我的代码:
def is_valid_move(board,row, column, digit):
if digit in board[row]:
print "Row already contains", digit
return (False)
else:
return (True)
for i in range(9):
if digit in board[i][row]:
print "Colum already contains", digit
return (False)
break
else:
return (True)
board = [[3,7,0,0,5,0,0,0,0],
[0,6,0,0,3,0,2,0,0],
[0,2,9,4,0,0,0,7,8],
[0,0,4,1,7,0,0,8,0],
[0,0,6,3,0,5,9,0,0],
[0,5,0,0,8,4,1,0,0],
[7,1,0,0,0,8,5,6,0],
[0,0,5,0,1,0,0,2,0],
[0,0,0,0,9,0,0,1,3]]
a=is_valid_move(board,1, 2, 9)
print a
我得到的输出:
True
知道如何检查框中是否已经有数字吗?
谢谢!
最佳答案
问题是一旦发现任何检查没有失败,您就会返回 true。因此,如果您有一个有效的行,那么您的检查就已经成功了,尽管该列可能充满了相同的数字。
所以基本上,删除所有 return True
行,并在所有检查结束后将一个单独的行放在最后。
还有一些事情:
- 不要在返回时用括号括起
True
或False
。 - 您不需要在
return
之后break
,因为后者已经结束了函数。 board[i][row]
以单个数字计算,因此使用digit in
的检查将不起作用,因为它需要一个可迭代对象。board[i][row]
应该是board[i][column]
因为第一个列表索引已经是行。
要检查 3x3 组的第三个条件是否有效,首先需要确定单元格属于哪个“框”,然后检查里面的所有数字:
# get the first row/column index of a block
blockRow = row // 3 * 3
blockColumn = column // 3 * 3
# check all 8 fields in the block
for r in range(blockRow, blockRow + 3):
for c in range(blockColumn, blockColumn + 3):
# skip the field we want to check
if r == row and c == column:
continue
if digit == board[r][c]:
return False
关于python - 数独检查条款,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13333591/