Created
July 13, 2012 16:48
-
-
Save hayd/3105928 to your computer and use it in GitHub Desktop.
Sudoku object - with hints
This file contains 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
#Note this requires the function solve_sudoku. | |
def Sudoku(grid): | |
def __init__(self): | |
self.grid = grid | |
self.solution = solve_sudoku(self.grid) | |
self.hints = self.get_hints() | |
def solvable(self): | |
return bool(self.solution) | |
def solved(self): | |
if self.solvable: | |
return self.grid is self.solution | |
def get_hints(self): | |
'''if solved or unsolvable, returns None | |
else: returns list of moves (row, col, value) to complete the sudoku | |
''' | |
if not self.solvable() or self.solved(): | |
return None | |
hints = [] | |
for row in range(9): | |
for col in range(9): | |
if self.grid[row][col] is 0: | |
hints.append( (row, col, self.solution[row][col]) ) | |
return hints | |
def random_hint(self): | |
'''If any more moves, returns a possible move (row, col, value) | |
else: returns None | |
''' | |
if self.hints: | |
hint = random.choice(hints) | |
return hint | |
def fill_in(self, row, col, value): | |
'''Tries to insert value into the empty square, grid[row][col]. | |
if grid[row][col] is not blank: returns None | |
else if inserting leads to no solutions: returns False | |
else if can insert value into grid[row][col]: returns True | |
else: returns None | |
''' | |
if not (row in range(9) and type(row) is int): | |
return None | |
if not (col in range(9) and type(col) is int): | |
return None | |
if not (value in range(1,10) and type(value) is int): | |
return None | |
if self.solvable() is False: | |
return False | |
if self.grid[row][col] is 0: | |
if self.solution[row][col] is value: | |
#value matches solution, so do not need to update solution | |
self.grid[row][col] = value | |
self.hints.remove((row,col,value)) | |
else: | |
#update is different from solution, so need to check | |
self.grid[row][col] = value | |
solved = solve_solution(self.grid) | |
if not solved: | |
self.grid[row][col] = 0 | |
return False | |
self.solution = solved | |
self.hints = self.get_hints() | |
return True | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment