You need to enable JavaScript to run this app. 将SMT2的appendo关系转换为Z3Py实现并自动枚举所有可行解
优惠活动
大模型
产品
解决方案
定价
更多

将SMT2的appendo关系转换为Z3Py实现并自动枚举所有可行解

Z3py实现appendo关系及自动枚举解方案

错误原因

你遇到的NameError: name 'l' is not defined报错,是因为定义Z3递归函数时,需要先显式声明形参为对应类型的常量对象,再将其传入RecAddDefinition的第二个参数列表,不能直接使用未定义的变量作为形参。

完整可运行代码

from z3 import *

# 定义泛型列表类型
def DeclareList(sort):
    List = Datatype(f'List_of_{sort.name()}')
    List.declare('cons', ('car', sort), ('cdr', List))
    List.declare('nil')
    return List.create()

IntList = DeclareList(IntSort())

# 先声明递归函数的形参
l = Const('l', IntList)
s = Const('s', IntList)
# 定义递归拼接函数appendo
appendo = RecFunction('appendo', IntList, IntList, IntList)
RecAddDefinition(appendo, [l, s], If(
    l == IntList.nil,
    s,
    IntList.cons(IntList.car(l), appendo(IntList.cdr(l), s))
))

# 声明待求解的变量a、b
a = Const('a', IntList)
b = Const('b', IntList)

# 目标拼接结果: [1, 2]
target = IntList.cons(1, IntList.cons(2, IntList.nil))

# 初始化求解器
solver = Solver()
solver.add(appendo(a, b) == target)

# 枚举所有符合条件的解
solution_cnt = 0
while solver.check() == sat:
    solution_cnt += 1
    model = solver.model()
    print(f"第{solution_cnt}组解:")
    print(f"a = {model[a]}")
    print(f"b = {model[b]}")
    print("---")
    # 添加约束排除当前解,避免重复枚举
    solver.add(Not(And(a == model[a], b == model[b])))

print(f"枚举完毕,共找到{solution_cnt}组有效解")

提示:如果运行报错请确认你使用的是4.8.0及以上版本的z3,旧版本对递归函数的支持存在缺陷。

运行输出示例

第1组解:
a = nil
b = cons(1, cons(2, nil))
---
第2组解:
a = cons(1, nil)
b = cons(2, nil)
---
第3组解:
a = cons(1, cons(2, nil))
b = nil
---
枚举完毕,共找到3组有效解

内容的提问来源于stack exchange,提问作者chansey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 21:42:01