示例#1
0
def cli_interface():
    """
    Command Line Interface
    """
    file = input('Enter file name with unsolved puzzle: ')
    try:
        sudoku = read_file(file)
    except FileNotFoundError:
        print('File does not exist')
        cli_interface()
    except ValueError:
        print('There are errors in the file')
        file_instruction.file_instruction()
        cli_interface()
    mode = int(input('Enter mode number: '))
    if mode != 1 and mode != 2 and mode != 3:
        print('Mode does not exist')
        cli_interface()
    else:
        if mode == 1:
            solve(sudoku)
            file_to_write = input(
                'Enter the name of the file to write solved puzzle: ')
            write_file(file_to_write, print_puzzle(sudoku))
        if mode == 2:
            solve_and_print.solve(sudoku)
            solve_and_print.print_puzzle(sudoku)
        if mode == 3:
            gui.main(sudoku)

        print('Enjoy! Your puzzle is solved\n')
示例#2
0
def sudoku_main(args):
    if not args:
        raise SudokuError("todo: show help")
    if args[0] == '-h':
        if not args[1]:
            raise SudokuError("File argument or input puzzle is required")
        if not os.path.isfile(args[1]):
            a = time.time()
            solve(args[1])
            print "\nSolved in " + str(time.time() - a) + "s !"
            return 0
        puzzles = file(args[1]).read().strip().split("\n")
        a = time.time()
        for puzzle in puzzles:
            solve(puzzle)
        print "\nAll solved in " + str(time.time() - a) + "s !"
        return 0
    if not args[0]:
        raise SudokuError("File argument or input puzzle is required")
    if not os.path.isfile(args[0]):
        return do_solve(args[0])
    puzzles = file(args[0]).read().strip().split("\n")
    a = time.time()
    for puzzle in puzzles:
        do_solve(puzzle)
    print "\nAll solved in " + str(time.time() - a) + "s !"
    return 0
示例#3
0
def timeSampler():

    timeE = []
    timeM = []
    timeH = []
    timeX = []
    
    for i in range(100):
        puzzle, solution = generate("Easy")
        start_time = time.clock()
        dict_values = sudoku.solve(puzzle)
        timeE.append(time.clock() - start_time)

        puzzle, solution = generate("Medium")
        start_time = time.clock()
        dict_values = sudoku.solve(puzzle)
        timeM.append(time.clock() - start_time)

        puzzle, solution = generate("Hard")
        start_time = time.clock()
        dict_values = sudoku.solve(puzzle)
        timeH.append(time.clock() - start_time)

        puzzle, solution = generate("Extreme")
        start_time = time.clock()
        dict_values = sudoku.solve(puzzle)
        timeX.append(time.clock() - start_time)

    times = {'Easy' : timeE, 'Medium' : timeM, 'Hard' : timeH, 'Extreme' : timeX}

    return times
示例#4
0
 def __init__(self, window):
     self.board = generate()
     self.solvedBoard = deepcopy(self.board)
     solve(self.solvedBoard)
     self.tiles = [[
         Tile(self.board[i][j], window, i * 60, j * 60) for j in range(9)
     ] for i in range(9)]
     self.window = window
示例#5
0
 def attempt(self):
     if self.double_check():
         self.clear_color()
         board = self.get_buttons()
         solve(0, 0, board)
         self.set_buttons(board)
     else:
         self.error_popup()
示例#6
0
    def solve(self, evt):
        '''
		Solve the current board, giving a graphical representation of how
		the solver program is attempting a solution.
		'''
        # This is where we call the function we wrote. Notice that self gets
        # passed in as the graphics parameter, so when solve calls
        # graphics.attempt, for example, it calls the attempt method of this
        # object.
        sudoku.solve(self.getBoard(), self)
        self.redraw(force=True)
示例#7
0
def test_generate():
    board = generate('easy')
    assert solve(board), "generate test #1 failed"

    board = generate('medium')
    assert solve(board), "generate test #2 failed"

    board = generate('hard')
    assert solve(board), "generate test #3 failed"

    board = generate('very_hard')
    assert solve(board), "generate test #4 failed"
示例#8
0
    def test_solve(self):
        grid = [
            ["5", "3", ".", ".", "7", ".", ".", ".", "."],
            ["6", ".", ".", "1", "9", "5", ".", ".", "."],
            [".", "9", "8", ".", ".", ".", ".", "6", "."],
            ["8", ".", ".", ".", "6", ".", ".", ".", "3"],
            ["4", ".", ".", "8", ".", "3", ".", ".", "1"],
            ["7", ".", ".", ".", "2", ".", ".", ".", "6"],
            [".", "6", ".", ".", ".", ".", "2", "8", "."],
            [".", ".", ".", "4", "1", "9", ".", ".", "5"],
            [".", ".", ".", ".", "8", ".", ".", "7", "9"],
        ]
        expected_solution = [
            ["5", "3", "4", "6", "7", "8", "9", "1", "2"],
            ["6", "7", "2", "1", "9", "5", "3", "4", "8"],
            ["1", "9", "8", "3", "4", "2", "5", "6", "7"],
            ["8", "5", "9", "7", "6", "1", "4", "2", "3"],
            ["4", "2", "6", "8", "5", "3", "7", "9", "1"],
            ["7", "1", "3", "9", "2", "4", "8", "5", "6"],
            ["9", "6", "1", "5", "3", "7", "2", "8", "4"],
            ["2", "8", "7", "4", "1", "9", "6", "3", "5"],
            ["3", "4", "5", "2", "8", "6", "1", "7", "9"],
        ]
        actual_solution = sudoku.solve(grid)
        self.assertEqual(expected_solution, actual_solution)

        grid = [
            ["6", "6", "1", "1", "1", "5", "8", "3", "7"],
            ["3", "5", "7", "8", "2", "6", "1", "4", "9"],
            ["1", "4", "8", "9", "3", ".", ".", "2", "6"],
            ["6", "3", "9", "5", "1", "2", "4", "7", "8"],
            ["5", ".", "1", "7", "6", ".", "3", ".", "2"],
            ["4", "7", "2", "3", ".", "8", "6", "1", "5"],
            ["9", "6", "4", "2", "8", "3", "7", "5", "1"],
            ["8", "1", ".", "4", "7", "9", "2", "6", "3"],
            ["7", "2", ".", "6", "5", "1", "9", "8", "."],
        ]
        expected_solution = [
            ["6", "6", "1", "1", "1", "5", "8", "3", "7"],
            ["3", "5", "7", "8", "2", "6", "1", "4", "9"],
            ["1", "4", "8", "9", "3", "7", "5", "2", "6"],
            ["6", "3", "9", "5", "1", "2", "4", "7", "8"],
            ["5", "8", "1", "7", "6", "4", "3", "9", "2"],
            ["4", "7", "2", "3", "9", "8", "6", "1", "5"],
            ["9", "6", "4", "2", "8", "3", "7", "5", "1"],
            ["8", "1", "5", "4", "7", "9", "2", "6", "3"],
            ["7", "2", "3", "6", "5", "1", "9", "8", "4"],
        ]
        actual_solution = sudoku.solve(grid)
        self.assertEqual(expected_solution, actual_solution)
示例#9
0
def main():
    #create an empty board
    board = [[0] * 9 for _ in range(9)]
    valid_sudoku = False

    while not valid_sudoku:
        try:
            generate(board)
            solve(board)
            valid_sudoku = True
        except RecursionError:
            valid_sudoku = False

    print_board(board)
示例#10
0
    def solve_sudoku(self):
        gridtemp = []
        with open(self.filename, 'r') as f:
            for line in f.readlines():
                gridtemp.append(list(line.rstrip()))
            for row in gridtemp:
                row2 = map(int, row)
                self.grid.append(row2)

        gridtemp = copy.deepcopy(self.grid)
        self.freq_d = calculate_frequency(gridtemp)
        starttime = time.time()
        sudokusolver.solve(gridtemp)
        self.solution = gridtemp
        self.runtime = time.time() - starttime
示例#11
0
def method():
    for i in range(0, 9):
        for j in range(0, 9):
            if not board[i][j].get().isdigit():
                new_board[i].append(0)
            else:
                new_board[i].append(int(board[i][j].get()))
    sudoku.solve(new_board)
    for i in range(0, 9):
        for j in range(0, 9):
            board[i][j].delete(0, END)
            board[i][j].insert(0, new_board[i][j])
            board[i][j].config(state=DISABLED)

    solve_button.grid_forget()
示例#12
0
 def test_escargot(self):
     """https://www.kristanix.com/sudokuepic/worlds-hardest-sudoku.php"""
     testgrid = '\n'.join((
         "1    7 9 ",
         " 3  2   8",
         "  96  5  ",
         "  53  9  ",
         " 1  8   2",
         "6    4   ",
         "3      1 ",
         " 4      7",
         "  7   3  ",
     ))
     grid = sudoku.initialise(testgrid)
     self.assertTrue(sudoku.solve(grid))
     self.assertEqual(grid, [
         [1, 6, 2, 8, 5, 7, 4, 9, 3],
         [5, 3, 4, 1, 2, 9, 6, 7, 8],
         [7, 8, 9, 6, 4, 3, 5, 2, 1],
         [4, 7, 5, 3, 1, 2, 9, 8, 6],
         [9, 1, 3, 5, 8, 6, 7, 4, 2],
         [6, 2, 8, 7, 9, 4, 1, 3, 5],
         [3, 5, 6, 4, 7, 8, 2, 1, 9],
         [2, 4, 1, 9, 3, 5, 8, 6, 7],
         [8, 9, 7, 2, 6, 1, 3, 5, 4],
     ])
示例#13
0
 def test_inkala(self):
     """https://www.telegraph.co.uk/news/science/science-news/9359579/Worlds-hardest-sudoku-can-you-crack-it.html"""
     testgrid = '\n'.join((
         "8        ",
         "  36     ",
         " 7  9 2  ",
         " 5   7   ",
         "    457  ",
         "   1   3 ",
         "  1    68",
         "  85   1 ",
         " 9    4  ",
     ))
     grid = sudoku.initialise(testgrid)
     self.assertTrue(sudoku.solve(grid))
     self.assertEqual(grid, [
         [8, 1, 2, 7, 5, 3, 6, 4, 9],
         [9, 4, 3, 6, 8, 2, 1, 7, 5],
         [6, 7, 5, 4, 9, 1, 2, 8, 3],
         [1, 5, 4, 2, 3, 7, 8, 9, 6],
         [3, 6, 9, 8, 4, 5, 7, 2, 1],
         [2, 8, 7, 1, 6, 9, 5, 3, 4],
         [5, 2, 1, 9, 7, 4, 3, 6, 8],
         [4, 3, 8, 5, 2, 6, 9, 1, 7],
         [7, 9, 6, 3, 1, 8, 4, 5, 2],
     ])
示例#14
0
 def test_1611984609(self):
     """http://www.websudoku.com/?level=4&set_id=1611984609"""
     testgrid = '\n'.join((
         "5   4 8  ",
         "   7     ",
         "63  82 1 ",
         "  1   2 9",
         "  6   5  ",
         "9 7   3  ",
         " 4 15  27",
         "     7   ",
         "  5 9   4",
     ))
     grid = sudoku.initialise(testgrid)
     self.assertTrue(sudoku.solve(grid))
     self.assertEqual(grid, [
         [5, 7, 2, 6, 4, 1, 8, 9, 3],
         [1, 9, 8, 7, 3, 5, 4, 6, 2],
         [6, 3, 4, 9, 8, 2, 7, 1, 5],
         [3, 5, 1, 8, 7, 6, 2, 4, 9],
         [4, 8, 6, 3, 2, 9, 5, 7, 1],
         [9, 2, 7, 5, 1, 4, 3, 8, 6],
         [8, 4, 9, 1, 5, 3, 6, 2, 7],
         [2, 1, 3, 4, 6, 7, 9, 5, 8],
         [7, 6, 5, 2, 9, 8, 1, 3, 4],
     ])
示例#15
0
def generateBoard2(difficulty=4):
    board = [['0' for x in xrange(9)] for x in xrange(9)]
    LB = LEVELS[difficulty][0]
    UB = LEVELS[difficulty][1]

    placedCtr = 0
    while True:
        if placedCtr > UB:
            placedCtr = 0
            board = [['0' for x in xrange(9)] for x in xrange(9)]
        if addElement(board) != None:
            placedCtr += 1
            sudoku.print_board(board)
            result = sudoku.solve(board)
            if sudoku.checkIfDone(result):
                # there is a solution
                print "nyan"
                break
            else:
                print "delai"
                sudoku.print_board(result)
        else:
            placedCtr = 0
            board = [['0' for x in xrange(9)] for x in xrange(9)]
    sudoku.print_board(board)
示例#16
0
 def set_val(self):
     value = 0
     for i in range(9):
         for j in range(9):
             if self.box_array[i][j].selected == True:
                 value = self.box_array[i][j].temp_value
                 row = i
                 column = j
     if value == 0:
         return 0
     else:
         if not valid_val(self.board_array, row, column, value):
             self.box_array[row][column].temp_value = 0
             return -20
         self.board_array[row][column] = value
         if solve(self.board_array):
             self.box_array[row][column].value = value
             for i in range(9):
                 for j in range(9):
                     self.board_array[i][j] = self.box_array[i][j].value
             self.box_array[row][column].selected = False
             return 100
         else:
             self.box_array[row][column].temp_value = 0
             for i in range(9):
                 for j in range(9):
                     self.board_array[i][j] = self.box_array[i][j].value
             return -20
示例#17
0
    def puzzle(self, problems, n):
        problem = inflate(problems[randint(0, len(problems))])
        solve(0, 0, problem)
        locs = list()
        for x in range(9):
            for y in range(9):
                locs.append((x, y))
        shuffle(locs)

        while n > 0:
            loc = locs.pop()
            x, y = loc
            problem[x][y] = 0
            n -= 1

        self.set_buttons(problem)
示例#18
0
def test_one():
    """
        Test that puzzle is solved correctly
    """

    puzzle = [[5,3,0,0,7,0,0,0,0],
              [6,0,0,1,9,5,0,0,0],
              [0,9,8,0,0,0,0,6,0],
              [8,0,0,0,6,0,0,0,3],
              [4,0,0,8,0,3,0,0,1],
              [7,0,0,0,2,0,0,0,6],
              [0,6,0,0,0,0,2,8,0],
              [0,0,0,4,1,9,0,0,5],
              [0,0,0,0,8,0,0,7,9]]

    solution = [[5,3,4,6,7,8,9,1,2],
                [6,7,2,1,9,5,3,4,8],
                [1,9,8,3,4,2,5,6,7],
                [8,5,9,7,6,1,4,2,3],
                [4,2,6,8,5,3,7,9,1],
                [7,1,3,9,2,4,8,5,6],
                [9,6,1,5,3,7,2,8,4],
                [2,8,7,4,1,9,6,3,5],
                [3,4,5,2,8,6,1,7,9]]

    attempt = solve(puzzle)
    for row in attempt:
        print(row)
    assert attempt == solution
    print("test one passed")
示例#19
0
def test_solve_1():
    input = parse_sudoku(
        "000000000009805100051907420290401065000000000140508093026709580005103600000000000"
    )
    output = solve(input)
    assert_equal(True, is_valid(output))
    assert_equal(True, compare(input, output))
示例#20
0
def solve(raw_image):
    # Take a raw image and return an augmented image if puzzle can be solved
    # Find the puzzle and paste on to raw_image
    puzzle_image, puzzle_offset_x, puzzle_offset_y = get_puzzle_from_image(raw_image)

    if puzzle_image is not None:
        # Recognize the numbers
        puzzle_repr, number_pictures = read_puzzle_from_image(raw_image, puzzle_image,
                                                              puzzle_offset_x, puzzle_offset_y)

        # If there are less than 17 numbers, we can't solve
        # or if there aren't 81 blocks
        print puzzle_repr
        if len(puzzle_repr) <> 81 or puzzle_repr.count('.') > 64:
            return

        # Solve the puzzle
        solved_puzzle = sudoku.solve(puzzle_repr)
        print solved_puzzle
        if not solved_puzzle:
            return

        print solved_puzzle
        # Place the solution on the original image and return
        augment_image_with_solution(raw_image, puzzle_offset_x, puzzle_offset_y,
                                    puzzle_image.width, puzzle_image.height, 
                                    puzzle_repr, solved_puzzle, number_pictures)
示例#21
0
 def test_easy_board(self):
     board = SudokuBoard([
         [None, None, None, None, None, None, None, 1, 2],
         [None, None, None, None, 3, 5, None, None, None],
         [None, None, None, 6, None, None, None, 7, None],
         [7, None, None, None, None, None, 3, None, None],
         [None, None, None, 4, None, None, 8, None, None],
         [1, None, None, None, None, None, None, None, None],
         [None, None, None, 1, 2, None, None, None, None],
         [None, 8, None, None, None, None, None, 4, None],
         [None, 5, None, None, None, None, 6, None, None],
     ])
     expected = SudokuBoard([
         [6, 7, 3, 8, 9, 4, 5, 1, 2],
         [9, 1, 2, 7, 3, 5, 4, 8, 6],
         [8, 4, 5, 6, 1, 2, 9, 7, 3],
         [7, 9, 8, 2, 6, 1, 3, 5, 4],
         [5, 2, 6, 4, 7, 3, 8, 9, 1],
         [1, 3, 4, 5, 8, 9, 2, 6, 7],
         [4, 6, 9, 1, 2, 8, 7, 3, 5],
         [2, 8, 7, 3, 5, 6, 1, 4, 9],
         [3, 5, 1, 9, 4, 7, 6, 2, 8],
     ])
     logger.debug(board)
     solution = solve(board)
     logger.debug(solution)
     self.assertEqual(solution, expected)
示例#22
0
def test_two():
    puzzle = [
     [9, 0, 0, 0, 8, 0, 0, 0, 1],
     [0, 0, 0, 4, 0, 6, 0, 0, 0],
     [0, 0, 5, 0, 7, 0, 3, 0, 0],
     [0, 6, 0, 0, 0, 0, 0, 4, 0],
     [4, 0, 1, 0, 6, 0, 5, 0, 8],
     [0, 9, 0, 0, 0, 0, 0, 2, 0],
     [0, 0, 7, 0, 3, 0, 2, 0, 0],
     [0, 0, 0, 7, 0, 5, 0, 0, 0],
     [1, 0, 0, 0, 4, 0, 0, 0, 7]]

    solution = [
     [9, 2, 6, 5, 8, 3, 4, 7, 1],
     [7, 1, 3, 4, 2, 6, 9, 8, 5],
     [8, 4, 5, 9, 7, 1, 3, 6, 2],
     [3, 6, 2, 8, 5, 7, 1, 4, 9],
     [4, 7, 1, 2, 6, 9, 5, 3, 8],
     [5, 9, 8, 3, 1, 4, 7, 2, 6],
     [6, 5, 7, 1, 3, 8, 2, 9, 4],
     [2, 8, 4, 7, 9, 5, 6, 1, 3],
     [1, 3, 9, 6, 4, 2, 8, 5, 7]]

    attempt = solve(puzzle)
    for row in attempt:
        print(row)
    assert attempt == solution
    print("test two passed")
示例#23
0
def generate_situation():
    matrix = [[0 for j in range(9)] for i in range(9)]
    all_situation = sudoku.solve(matrix, False)
    if all_situation:
        return all_situation[0]
    else:
        return None
示例#24
0
def solve():

    if request.method == 'GET':

        v = request.args.get('v')
        if v == None: v = 'CLASSIC'
        else: v = v.upper()

        return render_template('solve.html',
                               title='Solver',
                               variants=VARIANTS,
                               puzzle=form_grid(v),
                               v_code=v)

    elif request.method == 'POST':

        v = request.form['variant']
        g = grid_from_form(request.form, v)
        code = sudoku.grid_to_string(g, v, True)

        sc = None
        if request.form['submit_type'] == 'Solve':
            sc = sudoku.solve(g, v)
        else:
            sc = sudoku.score(g, v)

        return render_template('display.html',
                               title='Solver',
                               puzzle=render_grid(g, v),
                               variant=full_name(v),
                               v_code=v,
                               difficulty=sc,
                               code=code,
                               c_code=compress_code(code))
示例#25
0
 def test_hard_board(self):
     board = SudokuBoard([
         [8, None, None, None, None, None, None, None, None],
         [None, None, 3, 6, None, None, None, None, None],
         [None, 7, None, None, 9, None, 2, None, None],
         [None, 5, None, None, None, 7, None, None, None],
         [None, None, None, None, 4, 5, 7, None, None],
         [None, None, None, 1, None, None, None, 3, None],
         [None, None, 1, None, None, None, None, 6, 8],
         [None, None, 8, 5, None, None, None, 1, None],
         [None, 9, None, None, None, None, 4, None, None],
     ])
     expected = SudokuBoard([
         [8, 1, 2, 7, 5, 3, 6, 4, 9],
         [9, 4, 3, 6, 8, 2, 1, 7, 5],
         [6, 7, 5, 4, 9, 1, 2, 8, 3],
         [1, 5, 4, 2, 3, 7, 8, 9, 6],
         [3, 6, 9, 8, 4, 5, 7, 2, 1],
         [2, 8, 7, 1, 6, 9, 5, 3, 4],
         [5, 2, 1, 9, 7, 4, 3, 6, 8],
         [4, 3, 8, 5, 2, 6, 9, 1, 7],
         [7, 9, 6, 3, 1, 8, 4, 5, 2],
     ])
     logger.debug(board)
     solution = solve(board)
     logger.debug(solution)
     self.assertEqual(solution, expected)
示例#26
0
def test_solve_2():
    input = parse_sudoku(
        "003020600900305001001806400008102900700000008006708200002609500800203009005010300"
    )
    output = solve(input)
    assert_equal(True, is_valid(output))
    assert_equal(True, compare(input, output))
示例#27
0
def test_solve_3():
    input = parse_sudoku(
        "904200007010000000000706500000800090020904060040002000001607000000000030300005702"
    )
    output = solve(input)
    assert_equal(True, is_valid(output))
    assert_equal(True, compare(input, output))
示例#28
0
def main():
    ''' Driver function '''
    total = 0
    for puzzle in load_puzzles(src_file('e096')):
        solved = solve(puzzle)
        total += int(solved['A1'] + solved['A2'] + solved['A3'])
    print(total)
示例#29
0
def sudoku():
    #Getting input from
    board = request.json
    #Solving the board
    solution = solve(board)
    # Returning the response
    res = json.dumps(solution)
    return res
示例#30
0
def ocr_core(filename):
    """
    This function will handle the core OCR processing of images.
    """
    text = sudoku.solve(
        filename
    )  # We'll use Pillow's Image class to open the image and pytesseract to detect the string in the image
    return text  # Then we will print the text in the image
示例#31
0
    def test_evil_cases(self):
        lines = []
        with open('data/evil_10_sudoku.txt', 'rb') as input_handler:
            lines = input_handler.readlines()

        for puzzle in lines:
            puzzle = puzzle.strip()
            self.assertTrue( sudoku.is_solved(sudoku.solve(puzzle)))
示例#32
0
文件: test.py 项目: thushw/sudoku
 def solve_with_asserts(self, m, backTrack, backPropagate):
     if backTrack:
         p = sudoku.solve_with_backtracking(m, backPropagate)
     else:
         p = sudoku.solve(m)
     self.assertTrue(p is not None)
     self.assertTrue(sudoku.sudoku_solved(p))
     self.assertTrue(sudoku.sudoku_solved(m))
示例#33
0
    def test_solve(self):
        grid = grid_factory()
        l = range(1, 10)
        for i in xrange(0, 3):
            grid[i] = l
            for j in xrange(0, 3):
                l = copy.deepcopy(l)
                l.append(l.pop(0))
        printgrid(grid)

        self.assertTrue(solve(grid))
        self.assertTrue(solve(self.easy()))
        self.assertTrue(solve(self.hard()))
        grid = self.easy()
        grid[8][0] = 0
        grid[8][1] = 4
        self.assertFalse(solve(grid))
示例#34
0
def test_solve_infinite_solutions():
    # Okay, well... almost infinite. :-)
    grid = '.' * 81
    for count, solution in enumerate(su.solve(grid)):
        assert len(solution) == 81
        if count > 10:
            break
    assert count > 10
示例#35
0
def main():

    if len(sys.argv) != 2:
        usage()
        sys.exit()

    # Open image
    img = cv2.imread(sys.argv[1])

    gray = normalize_image(img)

    thresh = threshold_image(gray)

    # Locate the puzzle in the picture
    puzzle_cnt = find_puzzle(thresh)

    # Top left, top right, etc...
    tl, tr, bl, br = get_puzzle_corners(puzzle_cnt, *thresh.shape)

    # Prewarp the image for futher processing
    res = warp_image(tl, tr, bl, br, thresh)

    # Warp the puzzle in smaller segments to improve allignment of sudoku grid
    output = warp_puzzle(res)

    # Train the OCR model with training image
    ocr_model = train_ocr()

    # Extract sub-images of numbers in puzzle
    digits = extract_digits(output)

    # Get a string containing the detected sudoku puzzle
    puzzle_str = detect_numbers(ocr_model, digits)

    print("Detected Puzzle:")
    print("\n".join(textwrap.wrap(puzzle_str, 9)))
    print("")

    solution = sudoku.solve(puzzle_str)

    if len(solution) != 81:
        print("No solution was found.")
        sys.exit()

    print("Solved Puzzle:")
    print("\n".join(textwrap.wrap(solution, 9)))
    print("")

    # Write result to thresholded image
    output = cv2.cvtColor(output, cv2.COLOR_GRAY2BGR)
    output = draw_sol(output, list(solution), list(puzzle_str))

    cv2.imwrite("solution.png", output)
    print("Solution written to solution.png")

    out = Image.fromarray(output)
    out.show()
示例#36
0
def test_Puzzle_setup_random_grid_80():
    p = su.Puzzle()
    p.setup_random_grid(80)
    #    assert p.is_solved
    assert len(p.assigned_grid) == 81
    assert len(p.current_grid) == 81
    assert len(p.solved_grid) == 81
    all_solutions = list(su.solve(p.assigned_grid))
    assert len(all_solutions) == 1
    assert all_solutions[0] == p.solved_grid
示例#37
0
def testSolve():
    # Easy
    sudoku1 = [[4, 0, 0, 0, 0, 3, 0, 7, 0], [0, 0, 1, 0, 0, 9, 5, 0, 8],
               [0, 0, 0, 6, 0, 8, 4, 1, 3], [0, 1, 0, 9, 0, 0, 3, 0, 0],
               [0, 0, 0, 0, 5, 0, 0, 0, 0], [0, 0, 4, 0, 0, 6, 0, 8, 0],
               [7, 9, 2, 8, 0, 5, 0, 0, 0], [3, 0, 5, 4, 0, 0, 9, 0, 0],
               [0, 4, 0, 2, 0, 0, 8, 0, 5]]

    solved1 = [[4, 6, 8, 5, 1, 3, 2, 7, 9], [2, 3, 1, 7, 4, 9, 5, 6, 8],
               [5, 7, 9, 6, 2, 8, 4, 1, 3], [6, 1, 7, 9, 8, 2, 3, 5, 4],
               [8, 2, 3, 1, 5, 4, 7, 9, 6], [9, 5, 4, 3, 7, 6, 1, 8, 2],
               [7, 9, 2, 8, 3, 5, 6, 4, 1], [3, 8, 5, 4, 6, 1, 9, 2, 7],
               [1, 4, 6, 2, 9, 7, 8, 3, 5]]
    # Easy
    sudoku2 = [[0, 0, 0, 7, 0, 0, 6, 8, 9], [3, 0, 8, 0, 0, 0, 2, 0, 0],
               [0, 0, 0, 8, 1, 0, 0, 4, 0], [6, 0, 0, 0, 0, 0, 8, 0, 4],
               [8, 0, 0, 3, 4, 9, 0, 0, 5], [7, 0, 5, 0, 0, 0, 0, 0, 3],
               [0, 8, 0, 0, 7, 6, 0, 0, 0], [0, 0, 7, 0, 0, 0, 1, 0, 8],
               [9, 5, 1, 0, 0, 8, 0, 0, 0]]

    solved2 = [[1, 2, 4, 7, 5, 3, 6, 8, 9], [3, 7, 8, 9, 6, 4, 2, 5, 1],
               [5, 9, 6, 8, 1, 2, 3, 4, 7], [6, 3, 9, 5, 2, 7, 8, 1, 4],
               [8, 1, 2, 3, 4, 9, 7, 6, 5], [7, 4, 5, 6, 8, 1, 9, 2, 3],
               [4, 8, 3, 1, 7, 6, 5, 9, 2], [2, 6, 7, 4, 9, 5, 1, 3, 8],
               [9, 5, 1, 2, 3, 8, 4, 7, 6]]

    # Hard
    sudoku3 = [[9, 0, 0, 0, 0, 8, 0, 0, 0], [0, 0, 0, 0, 3, 2, 0, 0, 0],
               [6, 8, 0, 9, 0, 1, 0, 7, 0], [8, 0, 9, 5, 2, 0, 0, 3, 0],
               [2, 0, 0, 0, 0, 0, 0, 0, 5], [0, 4, 0, 0, 9, 3, 7, 0, 8],
               [0, 2, 0, 3, 0, 9, 0, 6, 4], [0, 0, 0, 2, 8, 0, 0, 0, 0],
               [0, 0, 0, 6, 0, 0, 0, 0, 3]]

    solved3 = [[9, 0, 0, 0, 0, 8, 0, 0, 0], [0, 0, 0, 0, 3, 2, 0, 0, 0],
               [6, 8, 0, 9, 0, 1, 0, 7, 2], [8, 0, 9, 5, 2, 0, 0, 3, 0],
               [2, 0, 0, 0, 0, 0, 0, 0, 5], [5, 4, 6, 1, 9, 3, 7, 2, 8],
               [0, 2, 0, 3, 0, 9, 0, 6, 4], [0, 0, 0, 2, 8, 0, 0, 0, 0],
               [0, 0, 0, 6, 0, 0, 0, 0, 3]]

    assert sudoku.solve(sudoku1) == solved1
    assert sudoku.solve(sudoku2) == solved2
    assert sudoku.solve(sudoku3) == solved3
示例#38
0
def main():
	with open("sudoku.txt") as f:
		contents = f.read()
		grids = contents.split("Grid")[1::]
		grids = ["".join([i for i in grid if i != "\n"]) for grid in grids]
	
	solved_grids = [sudoku.solve(grid) for grid in grids]
	solution = sum([int("".join([solution[square] 
						for square in ['A1', 'A2', 'A3']])) 
						for solution in solved_grids])
	print solution
示例#39
0
    def test_solve(self):
        with open("solved.su", "r") as f:
            dat = f.read().strip()
            solved = sudoku.loads(dat)

        with open("unsolved.su", "r") as f:
            dat = f.read().strip()
            unsolved = sudoku.loads(dat)

        hopefully_solved = sudoku.solve(unsolved)
        self.assertEqual(hopefully_solved, solved)
示例#40
0
文件: gui.py 项目: wekt0r/Sudoku-Game
    def on_solve(self):
        """
        Show solution to sudoku.

        Pre-filled tiles stay black.
        """
        solved, solution = solve(self.sudoku)
        if solved:
            self.sudoku = solution
            self._tiles = self._create_tiles(solution, SUDOKUX, SUDOKUY)
        self.on_check()
示例#41
0
  def test(self):
    with open(filepath) as f:
      grid_in = sudoku.read(f)
      self.assertIsNotNone(grid_in)

    grid_out = sudoku.solve(grid_in)
    self.assertIsNotNone(grid_out)

    filename, ext = os.path.splitext(filepath)
    expectation_filepath = filename + '_expected.csv'
    with open(expectation_filepath) as f:
      grid_expected = sudoku.read(f)
      self.assertEqual(grid_out, grid_expected)
示例#42
0
    def place(self, val):
        row, col = self.selected
        if self.cubes[row][col].value == 0:
            self.cubes[row][col].set(val)
            self.update_model()

            if valid(self.model, val, (row, col)) and solve(self.model):
                return True
            else:
                self.cubes[row][col].set(0)
                self.cubes[row][col].set_temp(0)
                self.update_model()
                return False
示例#43
0
def nextPuzzle(username) -> None:
    if not isUserExist(username):
        raise Exception(f'{username} - Пользователь не зарегестрирован')

    puzzle = sudoku.getLevelPuzzle(int(getUserLevel(username)))
    solution = sudoku.solve(puzzle)

    with open(path + username + '/' + 'puzzle.txt', 'w') as file:
        file.write(compressPuzzle(puzzle))
    with open(path + username + '/' + 'current.txt', 'w') as file:
        file.write(compressPuzzle(puzzle))
    with open(path + username + '/' + 'solution.txt', 'w') as file:
        file.write(compressPuzzle(solution))
示例#44
0
文件: p96.py 项目: bwo/euler
def solve():
    boards = []
    count = 0
    with open('sudoku.txt') as f:
        while count != 50:
            junk = f.readline()
            board = "\n".join([" ".join(f.readline().strip()) for _ in range(9)])
            boards.append(board)
            count += 1
    x = 0
    for board in boards:
        m = sudoku.solve(board)
        x += reduce(lambda acc, i: 10*acc+i, m[0][:3])
    return x
示例#45
0
 def play(self):
     browser = webdriver.Firefox()
     browser.get('http://view.websudoku.com/?level=%s' % self.game_level)
     grid_ids = ['f%s%s' % (row, col) for col in xrange(9) for row in xrange(9)]       
     grid = [browser.find_element_by_id(id).get_attribute('value') or '.' for id in grid_ids]
     solution = sudoku.solve(grid)
     solution_grid = (solution[k] for k in sorted(solution))
     for id, val in zip(grid_ids, solution_grid):
         browser.find_element_by_id(id).send_keys(val)
     browser.find_element_by_name('submit').click()
     assert 'Congratulations!' in browser.find_element_by_id('message').text
     if self.pause:
         time.sleep(self.pause)
     browser.quit()
     self._solution = solution
     self._puzzles_solved += 1
示例#46
0
文件: site.py 项目: hgeg/sudoku
def sudoku():
  if request.method=='POST':
    board = [[0 for e in xrange(9)] for e in xrange(9)]
    for k,v in request.form.items():
        board[int(k[1])-1][int(k[2])-1] = int(v) if v else 0
    lined = reduce(lambda e,f: e+f, board)
    off = lambda i: i+(i/3)*6
    line = lambda i: lined[off(i)*3:off(i)*3+3]+lined[off(i)*3+9:off(i)*3+12]+lined[off(i)*3+18:off(i)*3+21]
    listed = reduce(lambda e,f: e+f, [line(i) for i in xrange(9)])
    try:
        lined = solve(listed).values()
    except:
        lined = list('NO'+' '*7+'POSSIBLE '+'SOLUTIONS'+54*' ')
    values = reduce(lambda e,f: e+f, [line(i) for i in xrange(9)])
    keys = ['c%d%d'%(e,f) for e in xrange(1,10) for f in xrange(1,10)]
    solution = json.dumps(dict(zip(keys,values)))
    given = json.dumps(request.form)
    return render_template('sudoku.html',solution=solution,given=given)
  else:
    return render_template('sudoku.html')
示例#47
0
def generateBoard(difficulty=4):
    # generate a full puzzle, then remove the items to create different difficulty level
    board = [['0' for x in xrange(9)] for x in xrange(9)]
    while not sudoku.validateBoard(board):
        board = createFullPuzzle(board)
    
    sudoku.print_board(board)
    result = board
    lb = LEVELS[difficulty][0]
    ub = LEVELS[difficulty][1]
    num = LOWERBOUNDS[difficulty]

    removedCtr = 0
    while (81 - removedCtr) >= lb:
        i = random.randrange(0, 9)
        j = random.randrange(0, 9)
        if board[i][j] != '0':
            # check row
            if (9 - board[i].count('0')) > num:
                continue
            buf = []
            # check col
            for k in range(0, 9):
                buf.append(board[i][k])
            if (9 - buf.count('0')) > num:
                continue
            tmp = board[i][j]
            board[i][j] = '0'
            tmpboard = sudoku.solve(board)
            if checkSolution(tmpboard, result):
                removedCtr += 1
                if (81 - removedCtr) <= ub and random.randrange(0, 10) < 4:
                    break
            else:
                board[i][j] = tmp

    sudoku.print_board(board)
    sudoku.print_board(result)
示例#48
0
 def test_solve(self):        
     result = sudoku.read_sudoku("./data/result.txt")   #read the result 
     problem = sudoku.read_sudoku("./data/data1.txt")  #read the puzzle
     problemSets = sudoku.convertToSets(problem)
     self.assertTrue(sudoku.solve(problemSets))
     self.assertEqual(result, sudoku.convertToInts(problemSets))
示例#49
0
文件: 2.py 项目: thebend/sudoku
from timeit import timeit
import sudoku
import sudokuclass
import sudokun

board = sudoku.get_puzzle('puzzles/3.txt')
print sudoku.puzzle_string(board)
print

puzzle = sudoku.get_puzzle('puzzles/3.txt')
sudoku.solve(puzzle)
print sudoku.puzzle_string(puzzle)
print

puzzle = sudokuclass.Sudoku('puzzles/3.txt')
puzzle.solve()
print puzzle
print

puzzle = sudokun.Sudoku('puzzles/3.txt')
puzzle.solve()
print puzzle

print timeit(
    "sudoku.solve(sudoku.get_puzzle('puzzles/3.txt'))",
    setup='import sudoku',
    number=100
)
print timeit(
    "sudokuclass.Sudoku('puzzles/3.txt').solve()",
    setup='import sudokuclass',
示例#50
0

"""
SST browser-bot that solves sudoku puzzles.

see: http://testutils.org/sst
"""


from sudoku import solve
from sst.actions import *


go_to('http://view.websudoku.com/?level=4')  # evil

grid_ids = ['f%s%s' % (row, col) for col in xrange(9)
    for row in xrange(9)]

grid = [get_element(id=id).get_attribute('value') or '.'
    for id in grid_ids]

solution = solve(grid)

for (id, val) in zip(grid_ids,
        (solution[k] for k in sorted(solution))):
    write_textfield(id, val, check=False, clear=False)

click_element(get_element(name='submit'))

assert_text_contains('message', 'Congratulations!')
示例#51
0
#!/usr/bin/python

import sudoku
import sys

## main.
try:
    arg = sys.argv[1]
except (IndexError):
    arg = "board"

board = sudoku.read_board(arg)
done = sudoku.solve(board, 0)

sudoku.print_board(done)
示例#52
0
def solve(SDL):
    sudoku.display(sudoku.solve(SDL))
示例#53
0
文件: euler.py 项目: NacimKACEL/misc
if __name__ == '__main__':
    import sys
    import sudoku
    import time

    if len(sys.argv) != 3:
        sys.exit("Usage: <program> BT/SAT <file>.dat")

    Result = 0
    algo = sys.argv[1]
    fi = open(sys.argv[2])
    while True:
        if fi.readline()[0:4] != 'Grid':
            break
        M = []
        for j in range(9):
            M.append([int(c) for c in fi.readline().strip()])

        t0 = time.time()
        if algo == 'BT':
            solve(M)
        elif algo == 'SAT':
            sudoku.solve(M)
            Result += 100 * M[0][0] + 10 * M[0][1] + M[0][2]
        else:
            raise Exception("No algo: %r" % algo)
        print 'time: %8.3f sec' % (time.time() - t0)
    fi.close()
    print Result
示例#54
0
def test_solve_1():
    input = parse_sudoku("000000000009805100051907420290401065000000000140508093026709580005103600000000000")
    output = solve(input)
    assert_equal(True, is_valid(output))
    assert_equal(True, compare(input, output))
示例#55
0
def test_solve_2():
    input = parse_sudoku("003020600900305001001806400008102900700000008006708200002609500800203009005010300")
    output = solve(input)
    assert_equal(True, is_valid(output))
    assert_equal(True, compare(input, output))
示例#56
0
文件: main.py 项目: jkelleyy/sudoku
import sudoku
def print_solution(grid):
    for y in range(0,9):
        for x in range(0,9):
            print grid[x][y],
        print ""

def read_grid():
    grid = [[1,0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0,0]]
    for y in range(0,9):
        line = raw_input()
        counter = 0
        for thing in line.split():
            grid[counter][y]=int(thing)
            counter+=1
    return grid

print_solution(sudoku.solve(read_grid()))
示例#57
0
文件: t2.py 项目: Zarkonnen/Sudoku
 def test_solve(self):
     self.assertEqual(sudoku.solve(self.extremeSudokuGrid), self.extremeSudokuGridSolved)
示例#58
0
def evaluatePerformance():
    import cProfile
    global SDStr
    cProfile.run("Shudu(\"%s\").scanSDL()" % SDStr[1])        
    t=Shudu(SDStr[1])
    t.scanSDL()
    for i in range(0,81,9):
        print( t.sdList[i:i+9])
    
      
    cProfile.run("solve(\"%s\")" % SDStr[1])       
                   
def evaluateRunTime():
    global SDStr
    from timeit import Timer
    for SDL in SDStr:     
        print( SDL)
        t1 = Timer("Shudu(\"%s\").scanSDL()" % SDL, "from __main__ import Shudu")
        print( sum(t1.repeat(10, 1))/10)
    print( "==================================")
    for SDL in SDStr:
        SDL.replace("0", ".")
        print( SDL)
        t1 = Timer("solve(\"%s\")" % SDL, "from sudoku import solve")
        print( sum(t1.repeat(10, 1))/10)
    
if __name__ == '__main__' :
    evaluatePerformance()
    evaluateRunTime()
    sudoku.display(sudoku.solve("800000000003600000070090200050007000000045700000100030001000068008500010090000400"))        
示例#59
0
#6 9 5 	6 8 9
#2 5 3
#4 1 7 	5 1 4
#7 6 9
#3 8 2

#A well constructed Su Doku puzzle has a unique solution and can be solved by logic, although it may be necessary to employ "guess and test" methods in order to eliminate options (there is much contested opinion over this). The complexity of the search determines the difficulty of the puzzle; the example above is considered easy because it can be solved by straight forward direct deduction.

#The 6K text file, sudoku.txt (right click and 'Save Link/Target As...'), contains fifty different Su Doku puzzles ranging in difficulty, but all with unique solutions (the first puzzle in the file is the example above).

#By solving all fifty puzzles find the sum of the 3-digit numbers found in the top left corner of each solution grid; for example, 483 is the 3-digit number found in the top left corner of the solution grid above.

#Answer:
	#24702

from time import time; t=time()
from sudoku import solve
## See http://norvig.com/sudoku.html
## I just saw this one year ago

DATA = open('096-sudoku.txt').read().splitlines()
assert len(DATA) == 500
grids = [''.join(DATA[i+1:i+10]) for i in range(0, 500, 10)]

s = 0
for grid in grids:
    values = solve(grid)
    s += int(values['A1'])*100 + int(values['A2'])*10 + int(values['A3'])

print(s)#, time()-t)
示例#60
0
def test_solve_3():
    input = parse_sudoku("904200007010000000000706500000800090020904060040002000001607000000000030300005702")
    output = solve(input)
    assert_equal(True, is_valid(output))
    assert_equal(True, compare(input, output))