1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| from z3 import *
x = [[Int("x_%s_%s" % (i + 1, j + 1)) for j in range(9)] for i in range(9)]
bounds = [And(1 <= x[i][j], x[i][j] <= 9) for i in range(9) for j in range(9)]
rows = [Distinct(x[i]) for i in range(9)]
cols = [Distinct([x[i][j] for i in range(9)]) for j in range(9)]
sq = [Distinct([x[3 * ii + i][3 * jj + j] for i in range(3) for j in range(3)]) for ii in range(3) for jj in range(3)]
base_rules = bounds + rows + cols + sq
instance = ((0, 0, 0, 0, 9, 4, 0, 3, 0), (0, 0, 0, 5, 1, 0, 0, 0, 7), (0, 8, 9, 0, 0, 0, 0, 4, 0), (0, 0, 0, 0, 0, 0, 2, 0, 8), (0, 6, 0, 2, 0, 1, 0, 5, 0), (1, 0, 2, 0, 0, 0, 0, 0, 0), (0, 7, 0, 0, 0, 0, 5, 2, 0), (9, 0, 0, 0, 6, 5, 0, 0, 0), (0, 4, 0, 9, 7, 0, 0, 0, 0))
instance_c = [If(instance[i][j] == 0, True, x[i][j] == instance[i][j]) for i in range(9) for j in range(9)]
s = Solver()
s.add(base_rules + instance_c)
if s.check() == sat: m = s.model() r = [[m.evaluate(x[i][j]) for j in range(9)] for i in range(9)] print_matrix(r)
else: print("failed to solve")
|