103 lines
2.2 KiB
Python
103 lines
2.2 KiB
Python
#!/usr/bin/python3
|
|
|
|
"""This is a Sudoku Solver."""
|
|
|
|
from board import Board
|
|
|
|
|
|
def main():
|
|
"""Provided a string representing a Sudoku game, solve it."""
|
|
|
|
strings = [(
|
|
".2..785..\n"
|
|
"4...52...\n"
|
|
"..1..3.2.\n"
|
|
".....1...\n"
|
|
"7348.526.\n"
|
|
"2.9.67..5\n"
|
|
".687..3.9\n"
|
|
"342.1.7..\n"
|
|
"19..86..2\n"
|
|
), (
|
|
"..1..6435\n"
|
|
".....1...\n"
|
|
".5.47.98.\n"
|
|
"..2.8.7.9\n"
|
|
"..87..612\n"
|
|
".64.1..5.\n"
|
|
"91.3428.7\n"
|
|
".27....9.\n"
|
|
"6.3.9.5..\n"
|
|
), (
|
|
".....6...\n"
|
|
"..2.35.8.\n"
|
|
"....2..13\n"
|
|
".2....19.\n"
|
|
"93....7..\n"
|
|
"5....4...\n"
|
|
"1......7.\n"
|
|
".7...142.\n"
|
|
".9.4.3...\n"
|
|
), (
|
|
"...82....\n"
|
|
"...6.9..1\n"
|
|
"9.4..1...\n"
|
|
".9.7..28.\n"
|
|
".......57\n"
|
|
"7.5......\n"
|
|
".78962..5\n"
|
|
".2..8.7.3\n"
|
|
".6..74.2.\n"
|
|
), (
|
|
"4......1.\n"
|
|
".15.4.6..\n"
|
|
".....7...\n"
|
|
"...21...8\n"
|
|
"...734..2\n"
|
|
".3..8....\n"
|
|
"8.19...45\n"
|
|
".4....7..\n"
|
|
"2....3...\n"
|
|
), (
|
|
"3........\n"
|
|
".6...791.\n"
|
|
".....325.\n"
|
|
".19.645..\n"
|
|
".......6.\n"
|
|
".85......\n"
|
|
"...8.....\n"
|
|
"..1..97..\n"
|
|
"47..5....\n"
|
|
)]
|
|
|
|
for string in strings[2:-3]:
|
|
iterations = 0
|
|
while '.' in string:
|
|
iterations += 1
|
|
new_string = iterate_board(string)
|
|
assert new_string != string
|
|
string = new_string
|
|
print(f"Solved in {iterations} iterations.")
|
|
|
|
|
|
def iterate_board(string):
|
|
"""This function consists of one iteration through the solving process.
|
|
|
|
Return an updated string.
|
|
"""
|
|
|
|
board = Board(string, debug=False)
|
|
print(f"New board:\n{board}")
|
|
board.compute_possible_values()
|
|
board.intersect_lines_and_columns()
|
|
board.create_squares()
|
|
board.discard_with_grids()
|
|
board.compute_obligated_in_each_line()
|
|
board.compute_obligated_in_each_column()
|
|
print(f"New board:\n{board}")
|
|
|
|
return board.get_new_board()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|