#!/usr/bin/python3 """This is a Sudoku Solver.""" import argparse from board import Board def main(): """Provided a string representing a Sudoku game, solve it.""" parser = argparse.ArgumentParser() parser.add_argument('file', help='file containing the Sudoku to solve') args = parser.parse_args() sudoku_file = args.file strings = find_strings_in(sudoku_file) # default string if file wasn't computed if len(strings) == 0: strings = [( ".....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" )] for string in strings: solve_board(string, debug=False) def find_strings_in(sudoku_file: str) -> list: """Extract the Sudoku string from a file. Return a list of the Sudoku strings. """ strings: list = [] try: with open(sudoku_file, 'r') as sudokus: string = "" for line in sudokus.readlines(): if len(line) == 10: string += line elif len(line) == 1: strings.append(string) string = "" else: raise AssertionError("Invalid file") except FileNotFoundError: print("File not found, using default string.") return strings def solve_board(string: str, debug=False): """This function loops over the iteration process.""" board = Board(string, debug=debug) print(board) input("Hit ENTER to solve") iterations = 0 while '.' in string: iterations += 1 print(board) board.compute_possible_values() board.compute_obligated_values() string = board.update_string() board.update_board() print(board) print(f"Solved in {iterations} iterations.") input("Hit ENTER to continue") if __name__ == '__main__': main()