import z3
chicken, rabbits = z3.Ints('chicken rabbits')
z3.solve(chicken >= 1, # number of chicken
rabbits >= 1, # number of rabbits
chicken + rabbits == 35,
chicken * 2 + rabbits * 4 == 94)
[rabbits = 12, chicken = 23]
from z3 import *
circle, square, triangle = Ints('circle square triangle')
s = Solver()
s.add(circle+circle==10)
s.add(circle*square+square==12)
s.add(circle*square-triangle*circle==circle)
print(s.check())
print(s.model())
sat [triangle = 1, square = 2, circle = 5]
# 甲、乙、丙、丁、戊和己6个人正在超市排队交款。
# 己没有排在最后,而且他和最后一个人之间还有两个人;
# 戊不是最后一个人;
# 在甲的前面至少还有4个人,但他没有排在最后;
# 丁没有排在第一位,他前后至少都有两个人;
# 丙没有排在最前面,也没有排在最后。
# 请问,他们6个人的顺序是怎么排的?
from z3 import *
a, b, c, d, e, f = z3.Ints("a b c d e f")
z3.solve(
Distinct(a, b, c, d, e, f),
a >= 0, a <= 5,
b >= 0, b <= 5,
c >= 0, c <= 5,
d >= 0, d <= 5,
e >= 0, e <= 5,
f >= 0, f <= 5,
f != 5,
f == 2,
a >= 4,
a != 5,
d != 0,
d >= 2,
d <= 3,
c != 0,
c != 5)
[b = 5, a = 4, c = 1, d = 3, e = 0, f = 2]
# 八皇后问题
Q = [ Int('Q_%i' % (i + 1)) for i in range(8) ]
# Each queen is in a column {1, ... 8 }
val_c = [ And(1 <= Q[i], Q[i] <= 8) for i in range(8) ]
# At most one queen per column
col_c = [ Distinct(Q) ]
# Diagonal constraint
diag_c = [ If(i == j,
True,
And(Q[i] - Q[j] != i - j, Q[i] - Q[j] != j - i))
for i in range(8) for j in range(i) ]
solve(val_c + col_c + diag_c)
[Q_5 = 5, Q_8 = 4, Q_3 = 1, Q_2 = 3, Q_6 = 8, Q_4 = 7, Q_7 = 2, Q_1 = 6]
# 程序生产
from z3 import *
x = Int('x')
y = Int('y')
f = Function('f', IntSort(), IntSort())
s = Solver()
s.add(f(f(x)) == x, f(x) == y, x != y)
print(s.check())
m = s.model()
print("f(f(x)) =", m.evaluate(f(f(x))))
print("f(x) =", m.evaluate(f(x)))
sat f(f(x)) = 0 f(x) = 1