本文整理汇总了Python中sudoku.Sudoku.solve方法的典型用法代码示例。如果您正苦于以下问题:Python Sudoku.solve方法的具体用法?Python Sudoku.solve怎么用?Python Sudoku.solve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sudoku.Sudoku
的用法示例。
在下文中一共展示了Sudoku.solve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
def main():
with open('sudokus_3x3.txt', 'r') as myfile:
content = myfile.readlines()
# for each sudoku
content = [content[0]] # for testing
solved = 0
for i in range(len(content)):
line = content[i].strip()
sudoku = Sudoku(line)
sudoku.solve()
if sudoku.is_solved:
if ''.join(sudoku.sudoku) == borcic.sudoku99(line):
solved += 1
else:
print 'My solution:', ''.join(sudoku.sudoku)
print 'Expected: ', borcic.sudoku99(line)
raise RuntimeError('Got wrong solution!')
else:
print 'Couldnt finish Sudoku:\n', sudoku.to_string(), '\n'
print 'Candidates are:\n', '\n'.join(['\t|'.join(line) for line in sudoku.candidates])
print 'Solving sudoku', i, ':', sudoku.is_solved
print 'Solved', solved, 'from a total of', len(content), 'sudokus (' + str(round((solved*100.0)/len(content), 2)) + '%)'
示例2: test_solve
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
def test_solve(self):
# Setup
sudoku = Sudoku(puzzle=PUZZLE)
# Run
sudoku.solve()
# Verify
self.assertEqual(sudoku.puzzle, PUZZLE)
self.assertEqual(sudoku.solution, SOLUTION)
示例3: TestDLX
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
class TestDLX(unittest.TestCase):
def setUp(self):
self.sudoku = Sudoku(validate=True, pretty=False)
def read_line_by_line(self, filename, callback):
lines = open(filename)
for line in lines:
self.assertEqual(len(line), 82)
self.assertEqual(line[81], '\n')
callback(line[:81])
def assert_exception(self, line):
self.assertRaises(SudokuError, self.sudoku.solve, line)
def assert_valid(self, line):
grids = self.sudoku.solve(line)
self.assertEqual(len(grids), 1)
def test_bad_solutions(self):
filename = 'tests/data/collections/bad'
self.read_line_by_line(filename, self.assert_exception)
def test_valid_solutions(self):
filename = 'tests/data/collections/hardest'
self.read_line_by_line(filename, self.assert_valid)
示例4: solve_sudoku
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
def solve_sudoku(filename, filename_out=None):
"""Open a sudoku located in filename and solve it.
If filename_out is not None, the solved sudoku is saved.
Arguments:
filename -- the file name
Keyword arguments:
filename_out -- the output file name (default None)
"""
board = Board(filename=filename)
draw_board(board)
print _(u"Solving sudoku..."),
sys.stdout.flush()
# Use all the algos
sudoku = Sudoku(board, difficulty="hard")
success = False
if sudoku.solve():
print _(u"success!")
success = True
else:
print _(u"can't be solved!")
draw_board(sudoku.to_board())
if filename_out:
sudoku.to_board().save(filename_out)
return success
示例5: test_puzzlefy_l33t
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
def test_puzzlefy_l33t(self):
# Setup
sudoku = Sudoku(solution=SOLUTION, level="l33t")
# Run
sudoku.puzzlefy()
# Verify
empty_cells = sudoku.puzzle.count("0")
self.assertLessEqual(empty_cells, MAX_EMPTY_CELLS_L33T)
self.assertEqual(sudoku.solution, SOLUTION)
# Run
sudoku.solve()
# Verify
self.assertEqual(sudoku.solution, SOLUTION)
示例6: test_single_possibility
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
def test_single_possibility():
one_poss = "1, , , , , , , , ;\n" + \
" , , , 1, , , , , ;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , 1, ;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , 1;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , ;\n"
solution = "1, , , , , , , , ;\n" + \
" , , , 1, , , , , ;\n" + \
" , , , , , , 1, , ;\n" + \
" , , , , , , , 1, ;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , 1;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , ;\n"
sudoku = Sudoku()
sudoku.read_string(one_poss)
sudoku.solve()
assert_equal(str(sudoku), solution)
示例7: solve
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
def solve(self):
# Read values from the grid
values = [[self.get_value(row, col) for col in range(9)] for row in range(9)]
# Try to solve the Sudoku
solver = Sudoku(values)
if solver.solve():
for row in range(9):
for col in range(9):
self.text_inputs[9 * row + col].text = str(solver.get_value(row, col))
else:
error_message = ErrorMessage()
self.error_messages.append(error_message)
self.add_widget(error_message)
Clock.schedule_once(self.remove_error_message, 2)
示例8: test_hidden_twins
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
def test_hidden_twins():
boxPair = " , , , , , , , , ;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , ;\n" + \
" , , 3, , 5, 6, , , ;\n" + \
" , , , , 7, 8, 3, , ;\n" + \
" , , , 4, , , , , ;\n" + \
" , , , 9, , , , , ;\n" + \
" , , , , , , , , ;\n"
solution = " , , , , , , , , ;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , ;\n" + \
" , , , 3, , , , , ;\n" + \
" , , 3, , 5, 6, , , ;\n" + \
" , , , , 7, 8, 3, , ;\n" + \
" , , , 4, , , , , ;\n" + \
" , , , 9, , , , , ;\n" + \
" , , , , , , , , ;\n"
sudoku = Sudoku()
sudoku.read_string(boxPair)
sudoku.solve()
assert_equal(str(sudoku), solution)
示例9: test_subgroup_exclusion
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
def test_subgroup_exclusion():
intBoxColumn = " , , , , , , 4, 5, ;\n" + \
" , , , , , , 6, 7, ;\n" + \
" , , , , , 1, , 9, 8;\n" + \
" , , , , , , , 2, 9;\n" + \
" , , , , , 3, , , ;\n" + \
" , , , , , , , , 4;\n" + \
" , , , , , , , , 5;\n" + \
" , , , , , , , , 6;\n" + \
" , , , , , , , , ;\n"
solution = " , , , , , , 4, 5, ;\n" + \
" , , , , , , 6, 7, ;\n" + \
" , , , , , 1, , 9, 8;\n" + \
" , , , , , , , 2, 9;\n" + \
" , , , , , 3, , , 7;\n" + \
" , , , , , , , , 4;\n" + \
" , , , , , , , , 5;\n" + \
" , , , , , , , , 6;\n" + \
" , , , , , , , , ;\n"
sudoku = Sudoku()
sudoku.read_string(intBoxColumn)
sudoku.solve()
assert_equal(str(sudoku), solution)
示例10: test_only_choice
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
def test_only_choice():
one_choice = " , , , , 3, 4, , , ;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , 2, , 5;\n" + \
" , , , , , , , , 6;\n" + \
" , , , , , , , , 7;\n" + \
" , , , , , , , , 8;\n" + \
" , , , , , , , , 9;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , ;\n"
solution = " , , , , 3, 4, , , 1;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , 2, , 5;\n" + \
" , , , , , , , , 6;\n" + \
" , , , , , , , , 7;\n" + \
" , , , , , , , , 8;\n" + \
" , , , , , , , , 9;\n" + \
" , , , , , , , , ;\n" + \
" , , , , , , , , ;\n"
sudoku = Sudoku()
sudoku.read_string(one_choice)
sudoku.solve()
assert_equal(str(sudoku), solution)
示例11: SudokuTest
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
class SudokuTest(unittest.TestCase):
def setUp(self):
self.sudoku = Sudoku()
self.sudoku_puzzle = self.sudoku.parse_csv("puzzle.csv")
self.matrix = self.sudoku.group(self.sudoku_puzzle, 9)
self.location = (0, 0)
def test_puzzle_has_eighty_one_items(self):
self.assertEquals(len(self.sudoku_puzzle), 81)
def test_solve_puzzle(self):
answer = self.sudoku.solve(self.matrix)
self.sudoku.write_to_csv(answer)
dir = os.curdir
file_sys = os.listdir(dir)
self.assertIn("solution.csv", file_sys)
def test_solution_has_eighty_one_items(self):
solution = self.sudoku.parse_csv("solution.csv")
self.assertEquals(len(solution), 81)
def test_solution_is_correct(self):
solution = self.sudoku.parse_csv("solution.csv")
matrix = self.sudoku.group(solution, 9)
for line in matrix:
self.assertEquals(sorted(line), range(1, 10))
def test_solution_is_csv(self):
puzzle_file = "solution.csv"
self.assertTrue(puzzle_file.endswith("csv"))
def test_puzzle_elements_at_a_position(self):
col_elements = self.sudoku.get_col(self.matrix, self.location)
row_elements = self.sudoku.get_row(self.matrix, self.location)
block_elements = self.sudoku.get_block(self.matrix, self.location)
self.assertEquals(len(col_elements), 9)
self.assertEquals(len(row_elements), 9)
self.assertEquals(len(block_elements), 9)
def test_puzzle_elements_at_row_position_are_valid(self):
row_elements = self.sudoku.get_row(self.matrix, self.location)
self.assertEquals(row_elements, [0, 3, 5, 2, 9, 0, 8, 6, 4])
def test_puzzle_elements_at_col_position_are_valid(self):
col_elements = self.sudoku.get_col(self.matrix, self.location)
self.assertEquals(col_elements, [0, 0, 7, 2, 0, 0, 4, 3, 8])
def test_puzzle_elements_at_block_position_are_valid(self):
block_elements = self.sudoku.get_block(self.matrix, self.location)
self.assertEquals(block_elements, [0, 3, 5, 0, 8, 2, 7, 6, 4])
def test_puzzle_file_is_not_already_solved(self):
pos = self.sudoku.find_unsolved_location(self.matrix)
self.assertIsInstance(pos, tuple)
def test_unassinged_location(self):
pos = self.sudoku.find_unsolved_location(self.matrix)
self.assertEquals(pos, (0, 0))
def test_possible_value_is_correct(self):
value = list(
self.sudoku.find_possible_values(self.matrix, self.location)
)
self.assertEquals(value[0], 1)
def test_value_is_legal(self):
self.assertTrue(self.sudoku.is_legal(1, self.matrix, self.location))
示例12: GridWindow
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
class GridWindow(Gtk.Window):
def __init__(self, size=3):
Gtk.Window.__init__(self, title="Sudoku Example")
self.size = size
# This is an instance of a Sudoku solver
self.sudoku = Sudoku(size)
# Draw the window
self.table = [[Gtk.Entry() for _ in xrange(size**2)]
for _ in xrange(size**2)]
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.add(vbox)
grid = Gtk.Grid()
vbox.add(grid)
for row,lst in enumerate(self.table):
for col,entry in enumerate(lst):
entry.set_max_length(3)
entry.set_hexpand(True)
entry.set_vexpand(True)
entry.set_width_chars(2)
grid.attach(entry, col, row, 1, 1)
self.solve_button = Gtk.Button(label="Solve")
self.solve_button.set_hexpand(True)
vbox.add(self.solve_button)
self.solve_button.connect("clicked", self.solve)
self.clear_button = Gtk.Button(label="Clear")
self.clear_button.set_hexpand(True)
vbox.add(self.clear_button)
self.clear_button.connect("clicked", self.clear)
def clear(self, c): # pylint: disable=unused-argument
"""Reset the view emptying all cells"""
for lst in self.table:
for entry in lst:
entry.set_text("")
def solve(self, c):
"""Solve the problem using the currently-entered values"""
sq_size = self.size**2
# First, we compute the user constraints to feed into the Sudoku solver
constraints = []
for i in xrange(sq_size):
row = []
for j in xrange(sq_size):
txt = self.table[i][j].get_text()
try:
n = int(txt)
except ValueError:
n = 0
row.append(n)
constraints.append(row)
# Solve the problem
result = self.sudoku.solve(constraints)
if result is not None:
# Show the result
for r, lst in enumerate(result):
for c, val in enumerate(lst):
self.table[r][c].set_text(str(val))
else:
# The problem is unsolvable, show a message
dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK,
"The problem is unsolvable!")
dialog.run()
dialog.destroy()
示例13: Test
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
#.........这里部分代码省略.........
001806400
008102900
700000008
006708200
002609500
800203009
005010300"""
int_sudoku = []
for line in str_sudoku.split("\n"):
int_sudoku.append([int(i) for i in list(line.strip())])
self.s = Sudoku(int_sudoku)
def testHiddenLongerInRow_1(self):
# 2 IS HIDDEN LONGER
c1 = CellData(1)
c2 = CellData(4)
c3 = CellData(0)#
c3.suggests = [3, 5, 8]
c4 = CellData(6)
c5 = CellData(7)
c6 = CellData(0)#
c6.suggests = [5, ]
c7 = CellData(0)#
c7.suggests = [2, 3, 8]
c8 = CellData(9)
c9 = CellData(0)#
c9.suggests = [3, 8]
cells = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
result = self.s.find_hidden_longer(cells)
for cell in cells:
print cell.suggests
print result
def testHiddenLongerInRow_2(self):
# 4 IS HIDDEN LONGER
c1 = CellData(0)
c1.suggests = [7, ]
c2 = CellData(0)
c2.suggests = [3, 5]
c3 = CellData(1)
c4 = CellData(9)
c5 = CellData(0)
c5.suggests = [4, 5, 6]
c6 = CellData(0)
c6.suggests = [5, 6]
c7 = CellData(2)
c8 = CellData(8)
c9 = CellData(0)
c9.suggests = [3, 5, 7]
cells = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
result = self.s.find_hidden_longer(cells)
print result
def testHiddenLongerInRow_3_Two_hidden_longer(self):
# 4 IS HIDDEN LONGER
c1 = CellData(0)
c1.suggests = [7, 2]
c2 = CellData(0)
c2.suggests = [3, 5]
c3 = CellData(1)
c4 = CellData(9)
c5 = CellData(0)
c5.suggests = [4, 5, 6]
c6 = CellData(0)
c6.suggests = [5, 6]
c7 = CellData(2)
c8 = CellData(8)
c9 = CellData(0)
c9.suggests = [3, 5, 7]
cells = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
result = self.s.find_hidden_longer(cells)
print result
def testHiddenLongerInRow_2_NOT_FOUND(self):
c1 = CellData(0)
c1.suggests = [7, 4] # 4 TEST VALUE
c2 = CellData(0)
c2.suggests = [3, 5]
c3 = CellData(1)
c4 = CellData(9)
c5 = CellData(0)
c5.suggests = [4, 5, 6]
c6 = CellData(0)
c6.suggests = [5, 6]
c7 = CellData(2)
c8 = CellData(8)
c9 = CellData(0)
c9.suggests = [3, 5, 7]
cells = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
result = self.s.find_hidden_longer(cells)
print result
def testSolveMethod(self):
print "before"
self.s.draw_sudoku()
self.s.solve()
print "after"
self.s.draw_sudoku()
示例14: test_sudoku_class
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
#.........这里部分代码省略.........
puzzles_inconsistent.append(
"005079003" # first box inconsistent
"280000000"
"348000000"
"050680000"
"070204080"
"000013020"
"000000471"
"000000006"
"800790300"
)
puzzles_inconsistent.append(
"005079003" # middle box inconsistent
"200000000"
"348000000"
"050680000"
"070264080"
"000013020"
"000000471"
"000000006"
"800790300"
)
puzzles_inconsistent.append(
"005079003" # last row inconsistent
"200000000"
"348000000"
"050680000"
"070204080"
"000013020"
"000000471"
"000000006"
"800790308"
)
puzzles_inconsistent.append(
"005079003" # last col inconsistent
"200000000"
"348000000"
"050680000"
"070204080"
"000013026"
"000000471"
"000000006"
"800790300"
)
srtestpuzzle = ( # puzzle for the subregion test
"665679663" "266666666" "348666666" "656686666" "676264686" "666613626" "666666471" "666666666" "866796366"
)
for puzzle in puzzles_corrupt: # corrupt puzzles test
try:
Sudoku(instr=puzzle)
except SudokuInputError:
pass
else:
raise Exception("Bad input accepted")
for incons in puzzles_inconsistent: # inconsistent puzzles test
sudoku = Sudoku(instr=incons)
sudoku.solve()
assert not sudoku.is_consistent()
sudoku = Sudoku(instr=validpuzzle) # OK, let's see a valid puzzle
print sudoku
sudoku.solve()
print sudoku
assert sudoku.is_consistent()
print "human readable: \n{!s}".format(sudoku)
print "repr: \n {!r}".format(sudoku)
print "sudoku.regions: \n{}".format(sudoku.regions)
print "OK. Let's see how fast we can solve some puzzle collections."
# 50 easy, 95 hard
benchmarklist = [
("50 puzzles from Project Euler", "puzzles/euler_puzzles_50.txt", "puzzles/euler_solutions_50.txt"),
("95 hard puzzles", "puzzles/hard_puzzles_95.txt", "puzzles/hard_solutions_95.txt"),
]
# 5 hard
# benchmarklist = [("5 hard puzzles", "puzzles/hard_puzzles_5.txt", "puzzles/hard_solutions_5.txt") ] # for quick profiling
# 50 easy
# benchmarklist = [ ("50 puzzles from Project Euler", "puzzles/euler_puzzles_50.txt", "puzzles/euler_solutions_50.txt")]
for collection_name, path_puzzle, path_solution in benchmarklist:
print collection_name
with open(path_puzzle) as puzzles, open(path_solution, "w") as solutions:
before = time.clock()
collection = SudokuCollection(puzzles)
collection.solve_all(solutions, verbose=True) # TODO make verbosity a command line parameter
puzzleno = len(collection.sudokus) # number of sudokus, TODO: implement API
after = time.clock()
elapsed = after - before
average = elapsed / puzzleno
print "Solving {!s} puzzles took {!s} secs, avg: {!s} sec".format(
puzzleno, elapsed, average
) # TODO check results
print "Tests succesful!"
return True
示例15:
# 需要导入模块: from sudoku import Sudoku [as 别名]
# 或者: from sudoku.Sudoku import solve [as 别名]
#game=[[5,8,EMPTY,EMPTY,EMPTY,7,EMPTY,EMPTY,EMPTY],
# [EMPTY,EMPTY,6,4,5,EMPTY,8,EMPTY,EMPTY],
# [EMPTY,EMPTY,7,EMPTY,3,EMPTY,EMPTY,EMPTY,1],
# [1,EMPTY,EMPTY,EMPTY,EMPTY,9,EMPTY,2,EMPTY],
# [8,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,6],
# [EMPTY,6,EMPTY,2,EMPTY,EMPTY,EMPTY,EMPTY,4],
# [7,EMPTY,EMPTY,EMPTY,9,EMPTY,2,EMPTY,EMPTY],
# [EMPTY,EMPTY,1,EMPTY,2,3,9,EMPTY,EMPTY],
# [EMPTY,EMPTY,EMPTY,8,EMPTY,EMPTY,EMPTY,1,3]]
#
#sudoku=Sudoku(game)
#sudoku=sudoku.solve()
#print sudoku.game_state()
#lets try the most difficult: http://news.yahoo.com/solve-hardest-ever-sudoku-133055603--abc-news-topstories.html
# It take a while ;)
difficult=[[8,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY],
[EMPTY,EMPTY,3,6,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY],
[EMPTY,7,EMPTY,EMPTY,9,EMPTY,2,EMPTY,EMPTY],
[EMPTY,5,EMPTY,EMPTY,EMPTY,7,EMPTY,EMPTY,EMPTY],
[EMPTY,EMPTY,EMPTY,EMPTY,4,5,7,EMPTY,EMPTY],
[EMPTY,EMPTY,EMPTY,1,EMPTY,EMPTY,EMPTY,3,EMPTY],
[EMPTY,EMPTY,1,EMPTY,EMPTY,EMPTY,EMPTY,6,8],
[EMPTY,EMPTY,8,5,EMPTY,EMPTY,EMPTY,1,EMPTY],
[EMPTY,9,EMPTY,EMPTY,EMPTY,EMPTY,4,EMPTY,EMPTY]]
sudoku=Sudoku(difficult)
sudoku=sudoku.solve(True)
print sudoku.game_state()