Python3数独返回问题

时间:2014-06-24 01:10:27

标签: python python-3.x sudoku

使用下面的代码,我可以检查行和列,看看是否正确设置了Sudoku程序;该函数返回checkIt(行和列)的两个答案。有没有办法设置代码来检查行和列,然后返回“这个数独解决方案是正确的!”如果两者碰巧都是正确的(True),并且能够返回“列/行中的错误(.append(数字))”,如果任一行/ col checkIt函数解决方案恰好是错误的(False)?

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()

2 个答案:

答案 0 :(得分:1)

def checkIt(g):
   rows = checkRows(g)
   cols = checkCols(g)
   if rows == "good" and cols == "good":
       print(rowSuccess, colSuccess)
   elif rows=="good":
       print("Error in col: " + cols)
   elif cols=="good":
       print("Error in row: " + rows)
   else: # Both rows and cols have an error
       print("Error in row: " + rows)
       print("\nError in col: " + cols)

编辑:关于以下评论:如果出现错误,请尝试返回错误位置列表(只是在出现错误时将错误添加到列表中)。最后,如果列表大小为0(无错误),则返回True

如果一切正常,只需让checkRows(g)和checkCols(g)返回“good”,如果出现错误,则返回错误所在的行/列的编号。

答案 1 :(得分:0)

首先让checkRows返回冲突列表

rowConflicts = checkRows(g)
colConflicts = checkCols(g)

for conflict in rowConflicts:
    print("Error in row: " + conflict)
for conflict in colConflicts:
    print("Error in row: " + conflict)

if len(rowConflicts) = 0 and len(colConflicts) = 0:
    print("Success!")