def solver(): file = request.files['file'] if not os.path.isdir(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) if file and allowed_file(file.filename): color = request.form["color"] filename = secure_filename(file.filename) try: intersection= request.form["intersection"] except KeyError: intersection= None img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(img_path) results= None if intersection is None: print("intersection is none") results = solve(img_path, color, only_intersection=False) print(len(results)) else: print("intersection not none") results = solve(img_path, color) print(len(results)) os.system("rm -rf {}".format(UPLOAD_FOLDER)) if results: return str(len(results)) #render_template("result.html", len= len(results), results=results, filter_info="c= {}, int= {}".format(color,intersection)) return "Empty result :(" return render_template("file_upload_form.html", err_msg="Please select an image", title="Error")
def testSolver(): print("Testing sudoku solver...") board = [ [5, 0, 0, 0, 7, 0, 0, 8, 2], [0, 0, 0, 9, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 9, 3, 0], [0, 5, 0, 0, 0, 0, 8, 0, 0], [6, 7, 0, 0, 0, 0, 4, 0, 0], [0, 0, 0, 0, 0, 0, 0, 9, 3], [0, 0, 4, 3, 5, 0, 0, 0, 0], [9, 0, 6, 0, 0, 2, 0, 0, 0], [1, 0, 0, 0, 0, 6, 0, 0, 0] ] print("Testing sudoku1") _, solution = main.solve(board) printBoard(solution) board2 = [ [8, 2, 0, 0, 0, 0, 6, 0, 0], [1, 5, 0, 7, 0, 0, 0, 0, 9], [0, 0, 9, 0, 0, 0, 0, 0, 8], [6, 8, 1, 5, 0, 7, 0, 9, 4], [0, 9, 0, 1, 0, 4, 0, 8, 0], [3, 4, 0, 9, 0, 8, 1, 7, 6], [5, 0, 0, 0, 0, 0, 8, 0, 0], [2, 0, 0, 0, 0, 6, 0, 1, 3], [0, 0, 4, 0, 0, 0, 0, 6, 2] ] print("Testing sudoku2") solved, solution2 = main.solve(board2) printBoard(solution2)
def solve(self): # Use the solve function in the main script solve(self.model) # Update the cells with the new values to be displayed for i in range(self.rows): for j in range(self.cols): if self.cells[i][j].value == 0: self.cells[i][j].set(self.model[i][j], True) else: self.cells[i][j].set(self.model[i][j], False)
def main(n): lst = "".join(import_sudoku()).split("\n") open(path.join(path.abspath("Sudokus"), "solved.txt"), "w").close() cnt = 0 n = int(n) while cnt < n: try: solve(lst[cnt]) except SystemExit as e: export_sudoku(str(e)) l = "{0:.0f}".format((time() - start_time)*1000)[1:] print("Solved {0:.1f}% | {1}s {2}ms".format(((cnt+1)/n)*100, int(time() - start_time), l), end='\r') cnt += 1 print("Solved 100.0% | {0}s {1}ms".format(int(time() - start_time), l))
def test_example(self): example = """ 123 -> x 456 -> y x AND y -> d x OR y -> e x LSHIFT 2 -> f y RSHIFT 2 -> g NOT x -> h NOT y -> i """ lines = [line.strip() for line in example.splitlines() if line.strip()] instructions = main.parse_instructions(lines) wires = main.solve(instructions) expected = { 'd': 72, 'e': 507, 'f': 492, 'g': 114, 'h': 65412, 'i': 65079, 'x': 123, 'y': 456, } self.assertEqual(expected, wires)
def fromfile(): plt.clf() global points points = main.read_from_file("in1.txt") [centres, max_rad] = main.solve(points) update_text(centres, max_rad) fig.canvas.draw()
def test_simple_fold(self): simple_puzzle = {"snake" : [1, 1, 1, 1, 1, 1, 1], "shape" : {"len" : 2, "wid" : 2, "dep" : 2}} rectangle, s = load_puzzle(simple_puzzle) self.assertTrue(solve(rectangle, s))
def __init__(self, frame, window): super().__init__(frame) Title(master=self, text="Exemplul 4") messages = solve(epsilon, 4) for message in messages[1:]: Text(master=self, text=message) Button(master=self, text="Mergi inapoi", command=lambda: window.show_frame(Menu))
def genrand(): plt.clf() global points points = main.gen_points(100) [centres, max_rad] = main.solve(points) update_text(centres, max_rad) fig.canvas.draw()
def generate_sudoku() -> Board: """Generates a valid sudoku board with a few empty cells to be solved. The generate is done by getting a solution to an empty board. The implementation for the solver has been adjusted to choose guesses randomly which this functionality depends on to ensure different boards are returned each time. Raises: Exception: If no solution is found raises an exception; this is never expected to happen however added to pass strict typechecking. Returns: Board: Returns a valid sudoku board with a few missing cells to be solved. """ # can't multiply by 9 again (i.e. [[0]*9]*9) as that would copy the reference of the first # row for all of them, which mean any value in first row would be copied to # the rest empty_board = [[0] * 9 for _ in range(9)] solved_board = solve(empty_board) # this check is unnecessary in reality as we never expect a solution to not # be found for the empty board, it's just added to pass strict type checking if solved_board is None: raise Exception("No solution found") # number of cells to remove roughly controls the difficulty cells_to_remove_per_row = 5 for i in range(9): for j in random.sample(range(9), cells_to_remove_per_row): solved_board[i][j] = 0 return solved_board
def test_cases(): assert solve(0, 10) == 3 assert solve(10, 100) == 4 assert solve(100, 1000) == 12 assert solve(1000, 10000) == 20 assert solve(10000, 15000) == 6 assert solve(15000, 20000) == 9 assert solve(60000, 70000) == 15 assert solve(60000, 130000) == 55
def test(self): roots = [] for i in range(-5, 5): roots.append(solve(i)) self.assertEqual(roots, [ None, None, None, None, None, 0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0 ])
def test_example(self): example = """..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#""" lines = [line.strip() for line in example.splitlines()] result1 = main.solve(lines, [(3, 1)]) result2 = main.solve(lines, [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]) self.assertEqual(result1, 7) self.assertEqual(result2, 336)
def test_example_part_1(self): self.assertEqual( "1985", main.solve(keyboard=[ "123", "456", "789", ], instructions=["ULL", "RRDDD", "LURDL", "UUUUD"]))
def test_solve(self): self.assertEqual((1514, 404), main.solve([ "aaaaa-bbb-z-y-x-123[abxyz]", "a-b-c-d-e-f-g-h-987[abcde]", "not-a-real-room-404[oarel]", "totally-real-room-200[decoy]", ], search='bch o fsoz fcca'))
def test_solve_example_2(self): self.assertEqual( 641, main.solve(Stats( boss_hp=14, boss_damage=8, player_hp=10, player_mana=250, ), hard=False))
def test_solve_small(self): output = map(int, '5678910111213141516') _input = xrange(1, len(output) + 1) for i, o in zip(_input, output): expected = o actual = solve(i) msg = "Failed at input #%d: expected %d, actual %d" % ( i, expected, actual) self.assertEqual(expected, actual, msg=msg)
def test_solve_71_10(self): self.assertEqual( 1824, main.solve(Stats( boss_hp=71, boss_damage=10, player_hp=50, player_mana=500, ), hard=False))
def test_solve_55_8(self): self.assertEqual( 953, main.solve(Stats( boss_hp=55, boss_damage=8, player_hp=50, player_mana=500, ), hard=False))
def test_economy(self): map_ = [[".......", "######.", "......."]] labyrinth = Labyrinth3d(map_) info = solve(labyrinth, Location(0, 0), Location(2, 0), 1) expected = ["XXXXXXX", "######X", "XXXXXXX"] self.assertEqual(find_path(labyrinth, info), expected)
def test_example_part_2(self): self.assertEqual( "5DB3", main.solve(keyboard=[ "--1--", "-234-", "56789", "-ABC-", "--D--", ], instructions=["ULL", "RRDDD", "LURDL", "UUUUD"]))
def update(): plt.clf() global points, addpoints points.extend(addpoints) addpoints = [] [centres, max_rad] = main.solve(points) if max_rad == 0: start() return update_text(centres, max_rad) fig.canvas.draw()
def test_example(self): example = """ London to Dublin = 464 London to Belfast = 518 Dublin to Belfast = 141 """ lines = [line.strip() for line in example.splitlines() if line.strip()] distances = main.parse_distances(lines) shortest, longest = main.solve(distances) self.assertEqual(605, shortest) self.assertEqual(982, longest)
def runTests(dirs): baseResultPath = "results/" for directory in dirs: resultFilePath = baseResultPath + basename(directory) resultFile = open(resultFilePath, "w") testFilesNames = sorted(getFiles(directory)) for f in testFilesNames: testFile = open(f, "r") solution = solve(testFile) resultFile.write(str(solution) + "\n") print f + " " + str(solution) resultFile.close()
def runTests(dirs): baseResultPath = "results/" for directory in dirs: resultFilePath = baseResultPath + basename(directory) resultFile = open(resultFilePath,"w") testFilesNames = sorted(getFiles(directory)) for f in testFilesNames: testFile = open(f,"r") solution = solve(testFile) resultFile.write(str(solution) + "\n") print f + " " + str(solution) resultFile.close()
def place(self, val): row, col = self.selected if self.cubes[row][col].value == 0: self.cubes[row][col].set(val) self.update_board() if valid(self.board, val, (row, col)) and solve(self.board): return True else: self.cubes[row][col].set_temp(0) self.cubes[row][col].set(0) self.update_board()
def place(self, val): row, col = self.selected if self.cubes[col][row].value = 0: self.cubes[col][row].set(val) self.update_model() if valid(self.model, val, (col, row)) and solve(self.model): return True else: self.cubes[col][row].set(0) self.cubes[col][row].set_temp(0) self.update_model() return False
def test_int_to_hex(self): credit_cards = [ "1277421285754109", "5866044108627571", "7473986953606632", "4026467645830632", "2033092648604969" ] cens_cards = [] missing = [] for cnbr in credit_cards: for i in range(0, 16): missing += [cnbr[i]] cens_cards += [cnbr[:i] + 'X' + cnbr[(i + 1):]] found_missing = main.solve(cens_cards) self.assertEqual(list(found_missing), missing)
def test_examples(self): for input_file, output_file in self.CASEFILES: with self.subTest(input_file=input_file, output_file=output_file): with open(input_file, 'r') as fd: case_iter = iter(fd.read().splitlines()) with patch('builtins.input', iter(case_iter).__next__): inputs = parse() print("INPUTS>>>") print(inputs) actual_out = io.StringIO() with redirect_stdout(actual_out): solve(*inputs) print("OUTPUTS>>>") print(actual_out.getvalue()) with open(output_file, 'r') as fd: actual = actual_out.getvalue().split('\n')[:-1] expect = fd.read().splitlines() self.assertEqual(actual, expect)
def test_solve_basic_2(): unsolved = [[0, 7, 6, 0, 0, 4, 9, 3, 0], [2, 1, 0, 5, 0, 9, 0, 7, 0], [9, 0, 4, 0, 0, 7, 2, 0, 0], [0, 9, 0, 2, 0, 8, 0, 0, 7], [4, 0, 0, 1, 7, 5, 3, 6, 0], [0, 5, 0, 0, 4, 3, 8, 0, 0], [7, 0, 9, 0, 0, 1, 0, 8, 4], [0, 0, 0, 7, 0, 0, 1, 2, 3], [1, 0, 0, 4, 8, 0, 7, 0, 5]] solved = [[5, 7, 6, 8, 2, 4, 9, 3, 1], [2, 1, 8, 5, 3, 9, 4, 7, 6], [9, 3, 4, 6, 1, 7, 2, 5, 8], [3, 9, 1, 2, 6, 8, 5, 4, 7], [4, 8, 2, 1, 7, 5, 3, 6, 9], [6, 5, 7, 9, 4, 3, 8, 1, 2], [7, 2, 9, 3, 5, 1, 6, 8, 4], [8, 4, 5, 7, 9, 6, 1, 2, 3], [1, 6, 3, 4, 8, 2, 7, 9, 5]] assert solve(unsolved) == solved
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 find_possibility(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
def test_solve_big(self): size = 100000 output = reduce(operator.add, map(str, range(5, size))) output = map(int, output) # output will be # [5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2,...] for i, o in enumerate(output): i += 1 expected = o actual = solve(i) msg = "Failed at input #%d: expected %d, actual %d" % ( i, expected, actual) self.assertEqual(expected, actual, msg=msg)
def test_bomb_hard(self): map_ = ["........", "###..#..", "#.######", "...##..#", ".#...#..", "........"] labyrinth = Labyrinth3d([map_]) info = solve(labyrinth, Location(0, 0), Location(5, 0), 10) expected = ["XX......", "#B#..#..", "#X######", "XX.##..#", "X#...#..", "X......."] self.assertEqual(find_path(labyrinth, info), expected)
def test_easy(self): map_ = [[".#", "#."], ["..", ".."]] labyrinth = Labyrinth3d(map_) info = self.get_info([Location(0, 0, 0), Location(0, 0, 1), Location(0, 1, 1), Location(1, 1, 1), Location(1, 1, 0)], State(Location(1, 1, 0), 0)) solve_info = solve(labyrinth, Location(0, 0, 0), Location(1, 1, 0), 0) path = find_path(labyrinth, solve_info) expected = find_path(labyrinth, info) self.assertEqual(path, expected)