Created
February 15, 2019 16:34
-
-
Save ItsMeThom-zz/761f8df923fe7df50e5c805cf6c68c4c to your computer and use it in GitHub Desktop.
Experiments with sudoku validation (Mostly playing with list comprehensions and generators)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| board = [ | |
| [1,2,3,4,5,6,7,8,9], | |
| [5,7,8,1,3,9,6,2,4], | |
| [4,9,6,8,7,2,1,5,3], | |
| [9,5,2,3,8,1,4,6,7], | |
| [6,4,1,2,9,7,8,3,5], | |
| [3,8,7,5,6,4,2,9,1], | |
| [7,1,9,6,2,3,5,4,8], | |
| [8,6,4,9,1,5,3,7,2], | |
| [2,3,5,7,4,8,9,1,6] | |
| ] | |
| size = 9 | |
| block_size = 3 | |
| wanted = set([x for x in range(1, size + 1)]) | |
| def blocks(board): | |
| # iterate in 3x3 blocks starting @ 0,3,6 in the x & y | |
| for x, y in ((x,y) | |
| for y in range(0, size, block_size) | |
| for x in range(0, size, block_size)): | |
| yield [board[by][bx] | |
| for by in range(y, y + block_size) | |
| for bx in range(x, x + block_size)] | |
| def is_solved(board): | |
| # check rows have 1-9 | |
| for row in board: | |
| if wanted != set(row): | |
| return False | |
| # zip subarrays to make columns and check also | |
| for col in zip(*board): | |
| if wanted != set(col): | |
| return False | |
| # check the 3x3 blocks to ensure they are also good. | |
| for block in blocks(board): | |
| if wanted != set(block): | |
| return False | |
| # its a valid solution! | |
| return True | |
| print(is_solved(board)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment