使用下面的代碼,我可以檢查行和列,看看Sudoku程序是否設置正確,但是;該函數返回checkIt(行和列)的兩個答案。有沒有辦法設置代碼來檢查行和列,然後返回「這個數獨解決方案是正確的!」如果兩者碰巧是正確的(True),並且能夠返回「列/行中的錯誤(.append(number))」,如果row/col checkIt函數解決方案碰巧不正確(False)?Python3數獨返回問題
import sys
from scanner import *
def createList(size):
if size == 0: return []
else:
return [0] + createList(size -1)
def printGrid(gridlist):
for row in gridlist:
print (str(row)+"\n")
def rows(g):
return len(g)
def cols(g):
return len(g[0])
def printMatrix(g):
for i in range(0,rows(g),1):
for j in range(0,cols(g),1):
print(g[i][j],end=' ')
print('')
print('')
def readinput(filename,grid):
s = Scanner(filename)
r = s.readtoken()
while r != "":
r = int(r)
c = s.readint()
v = s.readint()
grid[r][c]=v
r = s.readtoken()
def checkRows(g):
for rows in g:
numbersInRow = []
for number in rows:
if number != 0 and number in numbersInRow:
return g.index(rows),False
else:
numbersInRow.append(number)
return "This Sudoku solution is correct!"
def checkCols(g):
for cols in g:
numbersInCol = []
for number in cols:
if number != 0 and number in numbersInCol:
return g.index(cols),False
else:
numbersInCol.append(number)
return True
def checkIt(g):
checkRows(g)
rowSuccess = checkRows(g)
print(rowSuccess)
checkCols(g)
colSuccess = checkCols(g)
print(colSuccess)
def main():
grid = createList(9)
for i in range(9):
grid[i] = createList(9)
readinput(sys.argv[1],grid)
printMatrix(grid)
checkIt(grid)
main()
難道你還需要檢查是否存在衝突的每個3×3格的列表? – Stephan
是的,但我應該逐步檢查每個衝突,行和列是冷杉,然後下一個子網格 – user3754670