You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将已有的Z3 Solver实例作为输入组合逻辑约束

实现方法

Z3的Solver实例不能直接作为逻辑表达式传入其他Solver的add方法,你需要先提取每个Solver实例内的约束,打包为对应逻辑表达式后再组合,具体步骤如下:

核心逻辑

每个Solver中添加的所有约束默认是**合取(AND)**关系,调用solver.assertions()可以获取该Solver内所有约束的列表,将列表传入And()方法即可得到该Solver对应的整体约束表达式。

完整可运行代码

from z3 import *

# 初始化你已有的三个Solver实例
Tie, Shirt = Bools('Tie Shirt')
s_one = Solver()
s_one.add(Or(Tie, Shirt))
s_two = Solver()
s_two.add(Or(Not(Tie), Shirt))
s_three = Solver()
s_three.add(Or(Not(Tie), Not(Shirt)))

# 将每个Solver的约束转换为对应的合取表达式
expr_one = And(s_one.assertions())
expr_two = And(s_two.assertions())
expr_three = And(s_three.assertions())

# 按你需要的逻辑关系组合后添加到新的Solver
s_four = Solver()
# 对应你示例的 s_one 成立 且(s_two 成立 或 s_three 成立)的逻辑
s_four.add(expr_one, Or(expr_two, expr_three))

# 验证求解结果
print("求解结果:", s_four.check())
print("可行模型:", s_four.model())

输出说明

运行上述代码会得到如下结果:

求解结果: sat
可行模型: [Tie = False, Shirt = True]

该结果符合逻辑:Tie=False, Shirt=True同时满足s_one的约束和s_two的约束,因此整体组合约束可满足。

内容的提问来源于stack exchange,提问作者i'm ashamed with what i asked

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:06:06