Learning Scientific Programming with Python (2nd edition)

E6.4: Checking a Sudoku grid for validity

A Sudoku square consists of a $9\times 9$ grid with entries such that each row, column and each of the 9 non-overlapping $3\times 3$ tiles contains the numbers 1—9 once only. The following program verifies that a provided grid is a valid Sudoku square.

import numpy as np

def check_sudoku(grid):
    """ Return True if grid is a valid Sudoku square, otherwise False. """
    for i in range(9):
        # j, k index top left hand corner of each 3x3 tile
        j, k = (i // 3) * 3, (i % 3) * 3
        if len(set(grid[i,:])) != 9 or len(set(grid[:,i])) != 9\
                   or len(set(grid[j:j+3, k:k+3].ravel())) != 9:
            return False
    return True

sudoku = """145327698
            839654127
            672918543
            496185372
            218473956
            753296481
            367542819
            984761235
            521839764"""
# Turn the provided string, sudoku, into an integer array
grid = np.array([[int(i) for i in line] for line in sudoku.split()])
print(grid)

if check_sudoku(grid):
    print('grid valid')
else:
    print('grid invalid')

Here we use the fact that an array of length 9 contains 9 unique elements if the set formed from these elements has cardinality 9. No check is made that the elements themselves are actually the numbers 1 – 9.

The output for the example grid provided in the code is:

[[1 4 5 3 2 7 6 9 8]
 [8 3 9 6 5 4 1 2 7]
 [6 7 2 9 1 8 5 4 3]
 [4 9 6 1 8 5 3 7 2]
 [2 1 8 4 7 3 9 5 6]
 [7 5 3 2 9 6 4 8 1]
 [3 6 7 5 4 2 8 1 9]
 [9 8 4 7 6 1 2 3 5]
 [5 2 1 8 3 9 7 6 4]]
grid valid