In Program 1, how can we program in python to check each block in Sudoku? The co
ID: 3693763 • Letter: I
Question
In Program 1, how can we program in python to check each block in Sudoku?
The code below is the sample code: q1.py
# Determines whether a Sudoku solution is valid.
def valid_rows(soln):
''' Returns True if each row is valid
and False otherwise.
'''
rows= [sum(t) for t in soln]
#print(rows)
total=rows.count(45)
if (total==9):
return True
else:
return False
def valid_cols(soln):
''' Returns True if each column
is valid and False otherwise.
'''
i = 0
length= len(soln)
for j in range(0,length):
total= 0
for l in range(0,length):
total = total + soln[l][j]
if total== 45:
i+=1
if i == 9:
return True
else:
return False
def valid_blocks(soln):
''' Checks each 3 x 3 block in the puzzle.
Returns True if each block is valid
and False otherwise.
'''
def valid_soln(soln):
''' Returns True if a Sudoku solution is valid and False
otherwise.
'''
# Check if rows are valid.
if not valid_rows(soln):
return False
# Check if columns are valid.
if not valid_cols(soln):
return False
# Check if 3x3 submatrices (or blocks) are valid.
if not valid_blocks(soln):
return False
# If all checks pass, then the solution is valid.
return True
def main():
''' The checking process begins here. '''
file_name = input('Enter filename: ')
input_file = open(file_name)
file_data = input_file.readlines()
input_file.close()
# sudoku_soln is populated with the data
# from the solution file. sudoku_soln is a
# tuple of tuples, where each tuple is of size
# 9. Draw a picture of sudoku_soln before you
# try to write the remaining code.
# Also, when adding values to a tuple, if we
# are only add one tuple, we must use a comma
# at the end (see Lines A & B).
sudoku_soln = ()
for line in file_data:
row = ()
for value in line.strip():
row += (int(value),) # Line A
sudoku_soln += (row,) # Line B
# Check and print results.
print()
if valid_soln(sudoku_soln):
print('Valid solution')
else:
print('Invalid solution')
main()
Explanation / Answer
Ans;
This is my solution:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.