Classic_Sudoku.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. #Row-Column Labels
  2. rows = 'ABCDEFGHI'
  3. cols = '123456789'
  4. def cross(a, b):
  5. """Make 2-char combos from two strings.
  6. Arguments: Two strings
  7. """
  8. return [s+t for s in a for t in b]
  9. #Defining Boxes
  10. boxes = cross(rows, cols)
  11. #Defining Units
  12. row_units = [cross(r, cols) for r in rows]
  13. column_units = [cross(rows, c) for c in cols]
  14. square_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]
  15. unitlist = row_units + column_units + square_units
  16. units = dict((s, [u for u in unitlist if s in u]) for s in boxes)
  17. peers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes)
  18. #Testing Example
  19. #grid = '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..'
  20. def grid_values_unsolved(grid):
  21. """Convert grid string into {<box>: <value>} dict with '.' value for empties.
  22. Arguments:
  23. grid: Sudoku grid in string form, 81 characters long
  24. Returns:
  25. Sudoku grid in dictionary form:
  26. - keys: Box labels, e.g. 'A1'
  27. - values: Value in corresponding box, e.g. '8', or '.' if it is empty
  28. """
  29. assert(len(grid)==81)
  30. return dict(zip(boxes, grid))
  31. def display(values):
  32. """Display the values as a 2-D grid.
  33. Input: The sudoku in dictionary form
  34. Output: None
  35. """
  36. width = 1+max(len(values[s]) for s in boxes)
  37. line = '+'.join(['-'*(width*3)]*3)
  38. for r in rows:
  39. print(''.join(values[r+c].center(width)+('|' if c in '36' else '')
  40. for c in cols))
  41. if r in 'CF': print(line)
  42. return
  43. def grid_values(grid):
  44. """Convert grid string into {<box>: <value>} dict with '123456789' value for empties.
  45. Args:
  46. grid: Sudoku grid in string form, 81 characters long
  47. Returns:
  48. Sudoku grid in dictionary form:
  49. - keys: Box labels, e.g. 'A1'
  50. - values: Value in corresponding box, e.g. '8', or '123456789' if it is empty
  51. """
  52. values = []
  53. all_digits = '123456789'
  54. for n in grid:
  55. if n == '.':
  56. values.append(all_digits)
  57. elif n in all_digits:
  58. values.append(n)
  59. assert len(values)==81
  60. return dict(zip(boxes, values))
  61. def eliminate(values):
  62. """Eliminate values from peers of each box with a single value.
  63. Go through all the boxes, and whenever there is a box with a single value,
  64. eliminate this value from the set of values of all its peers.
  65. Args:
  66. values: Sudoku in dictionary form
  67. Returns:
  68. Resulting Sudoku in dictionary form after eliminating values
  69. """
  70. #This will create a list of boxes that are solved
  71. solved_values = [box for box in values.keys() if len(values[box]) == 1]
  72. for box in solved_values:
  73. digit = values[box]
  74. for peer in peers[box]:
  75. values[peer] = values[peer].replace(digit,'')
  76. return values
  77. def only_choice(values):
  78. """Finalize all values that are the only choice for a unit.
  79. Go through all the units, and whenever there is a unit with a value
  80. that only fits in one box, assign the value to this box.
  81. Input: Sudoku in dictionary form.
  82. Output: Resulting Sudoku in dictionary form after filling in only choices.
  83. """
  84. for unit in unitlist:
  85. for digit in '123456789':
  86. dplaces = [box for box in unit if digit in values[box]]
  87. if len(dplaces) == 1:
  88. values[dplaces[0]] = digit
  89. return values
  90. def reduce_puzzle(values):
  91. """Iterate eliminate() and only_choice().
  92. If at some point, there is a box with no available values, return False.
  93. If the sudoku is solved, return the sudoku.
  94. If after an iteration of both functions, the sudoku remains the same, return the sudoku.
  95. Input: A sudoku in dictionary form.
  96. Output: The resulting sudoku in dictionary form.
  97. """
  98. stalled = False
  99. while not stalled:
  100. #Check how many boxes have a determined value
  101. solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])
  102. #Use the Eliminate Strategy
  103. values = eliminate(values)
  104. #Use the Only Choice Strategy
  105. values = only_choice(values)
  106. #Check how many boxes have a determined value, to compare
  107. solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])
  108. #If no new values were added, stop the loop.
  109. stalled = solved_values_before == solved_values_after
  110. #Sanity check, return False if there is a box with zero available values:
  111. if len([box for box in values.keys() if len(values[box]) == 0]):
  112. return False
  113. return values
  114. def search_puzzle(values):
  115. """Using depth-first search and propagation,
  116. create a search tree and solve the sudoku."""
  117. #Reduce the puzzle
  118. values = reduce_puzzle(values)
  119. if values is False:
  120. return False ##Failed early
  121. if all(len(values[s]) == 1 for s in boxes):
  122. return values ##Solved!
  123. #Choose one of the unfilled squares with the fewest possibilities
  124. n, s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)
  125. #print(n,s)
  126. #Recursion to solve each one of the resulting sudokus,
  127. #and if one returns a value (not False), return that answer!
  128. for value in values[s]:
  129. new_sudoku = values.copy()
  130. new_sudoku[s] = value
  131. attempt = search(new_sudoku)
  132. if attempt:
  133. return attempt
  134. if __name__ == '__main__':
  135. #Testing Example
  136. print("Enter the Sudoku values row-wise.\n\nAn example is given below:")
  137. print('..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..\n')
  138. grid = input("Enter the Sudoku string:\n")
  139. print('\n')
  140. display(grid_values_unsolved(grid))
  141. print("\n")
  142. display(search_puzzle(reduce_puzzle(grid_values(grid))))