Guest User

Untitled

a guest
Nov 15th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. class Board:
  2. WIDTH = 9
  3. HEIGHT = 9
  4.  
  5. def __init__(self):
  6. self.squares = [
  7. [5, 3, None, None, 7, None, None, None, None],
  8. [6, None, None, 1, 9, 5, None, None, None],
  9. [None, 9, 8, None, None, None, None, 6, None],
  10. [8, None, None, None, 6, None, None, None, 3],
  11. [4, None, None, 8, None, 3, None, None, 1],
  12. [7, None, None, None, 2, None, None, None, 6],
  13. [None, 6, None, None, None, None, 2, 8, None],
  14. [None, None, None, 4, 1, 9, None, None, 5],
  15. [None, None, None, None, 8, None, None, 7, 9]
  16. ]
  17.  
  18. def display(self):
  19. for row in self.squares:
  20. print([(val if val is not None else '?') for val in row])
  21.  
  22. def row_vals(self, x, y):
  23. return {val for val in self.squares[y] if val is not None}
  24.  
  25. def col_vals(self, x, y):
  26. return {row[x] for row in self.squares if row[x] is not None}
  27.  
  28. def sqr_vals(self, x, y):
  29. x = (x // 3) * 3
  30. y = (y // 3) * 3
  31.  
  32. return {
  33. self.squares[j][i] for j in range(y, y+3) for i in range(x, x+3)
  34. if self.squares[j][i] is not None
  35. }
  36.  
  37.  
  38. class Solver():
  39. POSSIBLE = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  40.  
  41. def __init__(self, board):
  42. self.board = board
  43.  
  44. def constrain(self):
  45. for y in range(self.board.HEIGHT):
  46. for x in range(self.board.WIDTH):
  47. if self.board.squares[y][x] is not None:
  48. continue
  49.  
  50. row_possible = self.POSSIBLE - self.board.row_vals(x, y)
  51. col_possible = self.POSSIBLE - self.board.col_vals(x, y)
  52. sqr_possible = self.POSSIBLE - self.board.sqr_vals(x, y)
  53. possible = row_possible & col_possible & sqr_possible
  54.  
  55. if len(possible) == 1:
  56. self.board.squares[y][x] = possible.pop()
  57.  
  58. def complete(self):
  59. for y in range(self.board.HEIGHT):
  60. for x in range(self.board.WIDTH):
  61. if self.board.squares[y][x] is None:
  62. return False
  63.  
  64. return True
  65.  
  66.  
  67. if __name__ == '__main__':
  68. board = Board()
  69. solver = Solver(board)
  70.  
  71. while not solver.complete():
  72. solver.constrain()
  73.  
  74. board.display()
Add Comment
Please, Sign In to add comment