Python Numpy Mini Projects: Sudoku Board Validator
Sudoku Board is mathematical board which has dimensions 9x9. You have to fill the numbers from 1 to 9 without duplication in columns or rows.
Validation can be done by as follows.
- · Each row should have numbers 1-9 without duplicates.
- · Each column needs to filled with numbers 1-9 without repetition.
- · In the same way, each sub-grid should be filled with numbers 1-9 without overlapping.
Program implementation:
- This code starts from importing numpy library.
- Two functions are created for validating the sudoku board.one is for shape. Another one is for elements.
- Input of the sudoku board is created with elements.
- First, shape is checked for number of rows and columns.
- Next one is for each row, each column and sub grid.
- Each one of the groups should be filled with 1to 9 without any repetition.
- Finally, the output is printed.
Code:
import numpy as np1
def is_valid_group(group):
"""Check
if a row, column, or sub grid contains digits 1-9 exactly
once."""
return np1.array_equal(np1.sort(group),
np1.arange(1, 10))
def validate_sudoku(board):
board = np1.array(board)
# Checking for
board shape
if board.shape != (9,
9):
return False, "Board
must be 9x9."
# Checking for
rows
for i in range(9):
if not is_valid_group(board[i]):
return False,
f"Invalid row {i+1}"
# Checking for
columns
for j in range(9):
if not is_valid_group(board[:,
j]):
return False,
f"Invalid column {j+1}"
# Check 3x3
sub-grids
for row in range(0,
9, 3):
for col in range(0,
9, 3):
box = board[row:row+3,
col:col+3].flatten()
if not is_valid_group(box):
return
False, f"Invalid 3x3 box at ({row}, {col})"
return True, "Yes,
the board is Valid Sudoku Board"
# Example Sudoku Board
sudoku_board = [
[9,7,8,2,4,6,5,3,1],
[6,4,2,1,3,5,9,7,8],
[5,3,1,8,7,9,6,4,2],
[3,6,5,4,1,2,8,9,7],
[8,9,7,5,6,3,2,1,4],
[2,1,4,7,9,8,3,6,5],
[1,2,3,9,8,7,4,5,6],
[7,8,9,6,5,4,1,2,3],
[4,5,6,3,2,1,7,8,9]
]
valid, message = validate_sudoku(sudoku_board)
print(message)
Output:
Yes, the board is Valid Sudoku Board
That’s all. The python numpy mini project to implement the
sudoku Board validator was done successfully. Keep Coding!!!!
Comments
Post a Comment