我已经在数独求解器上工作了一段时间,我只是实现了检测数字是否只能有一个空格而无法执行的功能。另外,以前的一些代码似乎根本没有用。
def square_solver(board):
"""Remove confirmed values from the possible values in the squares"""
global possibleBoard
# Sets up a modulator to multiply by to get the 3x3 grid of one square with the first value being the rows and the second being the column
blockNum = [0, 0]
for _ in range(9):
# A loop that checks the 9 numbers in one of the squares
for x in range(3):
for y in range(3):
if not board[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y] == " ": # Checks if that square a number
# Checks all the empty spots in one of the squares for that number, then removes them
for z in range(3):
for w in range(3):
try:
# Removes the number from the possible board
possibleBoard[(blockNum[0] * 3) + z][(blockNum[1] * 3) + w].remove(
board[(blockNum[0] * 3) + x][(blockNum[1] * 3) + y])
# If it can't do anything, run this
except (ValueError, AttributeError):
pass
blockNum = block_num(blockNum)
return board
counter = [0] * 9
blockNum = [0, 0]
for _ in range(9):
for x in range(3):
for y in range(3):
# Checks the possible board and counts how many time a possible number appears
if type(possibleBoard[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y]) == list:
for z in range(len(possibleBoard[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y])):
counter[possibleBoard[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y][z] - 1] += 1
for x in range(len(counter)):
# Checks to see if there was any times only one number appeared
if counter[x] == 1:
for y in range(3):
for z in range(3):
try:
# Finds the solo number, and makes that number definite
if (x + 1) in possibleBoard[(blockNum[0] * 3) + y][(blockNum[0] * 3) + z]:
board[(blockNum[0] * 3) + y][(blockNum[0] * 3) + z] = x + 1
except TypeError:
pass
blockNum = block_num(blockNum)
# Rests the counter
counter = [0] * 9
我已经重写了这两部分代码,而且两次都没有解决数独难题。我无法弄清楚出什么问题了,但我认为这可能与board[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y]
部分有关。
完整代码为here。
您的代码段为board[(blockNum[0] * 3) + x][(blockNum[0] * 3) + y]
,所有问题均源于它应该为board[(blockNum[0] * 3) + x][(blockNum[1] * 3) + y]
。由于它要对具有相同编号的行和列进行计数,因此只会沿对角线移动。更改这些位置可解决问题。