With the code below I can check rows and columns to see if the Sudoku program is set up correctly, however; the function returns two answers for checkIt (rows and cols). Is there a way to set up the code to check both rows and cols and then return with "This Sudoku solution is correct!" if both happen to be correct(True) along with being able to return with "Error in column/row (.append(number))" if either row/col checkIt function solution happened to be incorrect(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()
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)
EDIT: With regards to comment below: Try returning a list of error positions if error(s) come up (just append an error to the list when it comes up). At the end, if the list is of size 0 (no errors) just return True
Simply have checkRows(g) and checkCols(g) return "good" if everything is fine and the number of the row/column where the error is if an error comes up.
First make checkRows return a list of conflicts
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!")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.