我需要检查用户插入的数字是否已经在colum、行或“块”中(仍在处理最后一部分)。因为某种原因,这些支票不起作用,我也不明白为什么?
我在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知道怎么检查号码是否已经在盒子里了吗?
谢谢!
发布于 2012-11-11 17:35:48
问题是,一旦找到没有失败的检查,就返回true。因此,如果您有一个有效的行,您的检查已经成功,尽管该列可能已经满了相同的编号。
因此,基本上,在所有检查结束后,删除所有return True行,并将一个行放在最末尾。
还有几件事:
True或False括号。break之后使用return,因为后者已经结束了这个函数。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发布于 2012-11-11 18:43:13
如果您想为用户创建sudoku,请使用以下技巧来删除数字--它的镜像模式(对不起,我的英语)
(1 _34)
(7 _ 5 6) https://stackoverflow.com/questions/13333591
复制相似问题