Sudoku Board Verification

#!/usr/bin/env python
import pprint

# ----------------------------------------------------------------------------#
# Define a 9x9 matrix representing a Sudoku board
matrix1 = [
    [7, 1, 8, 5, 3, 2, 9, 4, 6],
    [5, 3, 2, 6, 9, 4, 1, 8, 7],
    [6, 9, 4, 7, 1, 8, 3, 2, 5],
    [1, 2, 7, 3, 4, 5, 8, 6, 9],
    [9, 8, 6, 1, 2, 7, 4, 5, 3],
    [3, 4, 5, 9, 8, 6, 2, 7, 1],
    [4, 6, 3, 8, 7, 9, 5, 1, 2],
    [8, 7, 9, 2, 5, 1, 6, 3, 4],
    [2, 5, 1, 4, 6, 3, 7, 9, 8],
]

# ----------------------------------------------------------------------------#
def verify_sudoku_board(board, value):
    """
    Verifies whether a given 9x9 Sudoku board is valid by checking that
    each row, column, and 3x3 sub-grid (window) sums to a specified value.

    Args:
        board (list of list of int): The 9x9 Sudoku board represented as a list of lists.
        value (int): The expected sum of each row, column, and 3x3 sub-grid.

    Returns:
        bool: True if the board is valid according to Sudoku rules, False otherwise.
    """
    
    # Verify each row sums to the given value
    for row in range(0, 9):
        if sum(board[row]) != value:
            return False

    # Verify each column sums to the given value
    for col in range(0, 9):
        total = 0
        for row in range(0, 9):
            total += board[row][col]
            # After finishing a column, check if the total sum matches the expected value
            if row == 8:
                if total != value:
                    return False

    # Verify each 3x3 sub-grid (window) sums to the given value
    for start in range(0, 9, 3):
        total = 0
        for col in range(start, start + 3):
            for row in range(start, start + 3):
                total += board[row][col]

        if total != value:
            return False

    return True

# ----------------------------------------------------------------------------#
if __name__ == "__main__":
    pp = pprint.PrettyPrinter()
    pp.pprint(matrix1)
    
    result = verify_sudoku_board(matrix1, 45)
    print(result)

Explanation

Matrix Definition (matrix1):

This is a 9x9 matrix representing a completed Sudoku board. Each inner list represents a row in the Sudoku puzzle.

Function verify_sudoku_board(board, value):

Purpose: This function checks if a given 9x9 Sudoku board is valid. It verifies that:

Parameters:

Returns:

True if the board is valid according to the above conditions, otherwise False.

Logic:

Main Block (__main__):

Purpose: To execute the script and verify the given Sudoku board.

Steps:

Example Output:

Given the provided Sudoku matrix, the function will check each row, column, and 3x3 sub-grid. If all checks pass (i.e., all sums equal 45), it will print True, indicating that the Sudoku board is valid.