Skip to content

Instantly share code, notes, and snippets.

@aksnell
Created June 24, 2020 14:19
Show Gist options
  • Save aksnell/d4f8eb9dcafa2869adf0f512c51cb657 to your computer and use it in GitHub Desktop.
Save aksnell/d4f8eb9dcafa2869adf0f512c51cb657 to your computer and use it in GitHub Desktop.
def sudoku(puzzle):
class Board(object):
def __init__(self, parse_board):
self.board = parse_board
self.row_list = {i: set(self.board[i]) for i in range(0,9)}
self.col_list = {i: set(x[i] for x in self.board) for i in range(0,9)}
self.grid_list = {i: list(self.yieldGrids())[i] for i in range(0,9)}
self.tile_list = list(self.insertTiles())
def insertTiles(self):
for row_index, row in enumerate(self.board):
for col_index, tile in enumerate(row):
if self.board[row_index][col_index] == 0:
yield Tile(row_index,col_index)
def yieldGrids(self):
for col_index in range(0,len(self.board),3):
for row_index in range(0,len(self.board),3):
for grid in [[self.board[col_index][row_index:row_index + 3],
self.board[col_index + 1][row_index:row_index + 3],
self.board[col_index + 2][row_index:row_index + 3]]]:
yield set([l for x in grid for l in x])
def updateTiles(self):
for tile in self.tile_list:
if tile.val == 0:
tile.updateTiles()
else:
self.tile_list.remove(tile)
def Solve(self):
self.updateTiles()
def _solve():
for tile in self.tile_list:
yield tile.attemptSolve()
if False in list(_solve()):
self.Solve()
else:
return True
class Tile(object):
def __init__(self, row, col):
self.val = 0
self.row = row
self.col = col
self.grid = self.getGrid()
self.rejected_values = None
def updateTiles(self):
def _updateTiles():
value_list = [list(board.row_list[self.row]) +
list(board.col_list[self.col]) +
list(board.grid_list[self.grid])]
for item in value_list:
for subitem in item:
yield subitem
self.rejected_values = set(filter(lambda x: x is not 0, list(_updateTiles())))
def attemptSolve(self):
if self.val == 0:
if len(self.rejected_values) == 8:
for i in set(range(1,10)):
if i not in self.rejected_values:
self.val = i
board.col_list[self.col].add(self.val)
board.row_list[self.row].add(self.val)
board.grid_list[self.grid].add(self.val)
board.board[self.row][self.col] = self.val
return True
else:
return False
def getGrid(self):
grid_mod = 0
if self.col > 2 and self.col < 6: grid_mod = 1
elif self.col > 5: grid_mod = 2
if self.row > 2 and self.row < 6: return 3 + grid_mod
elif self.row > 5: return 6 + grid_mod
else: return grid_mod
board = Board(puzzle)
board.Solve()
return(board.board)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment