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

如何用Sympy判断布尔表达式ANF单项式中是否含指定变量

从Sympy生成的ANF中提取含特定变量的单项式

针对需求,可通过Sympy表达式的结构属性拆分ANF,再筛选出包含目标变量的单项式,具体实现如下:

实现步骤

  1. 拆分ANF的单项式:Sympy生成的ANF由Xor连接若干单项式(每个单项式为And连接的变量或单个变量),通过表达式类型判断是否为XOR结构,进而提取所有单项式。
  2. 筛选目标单项式:遍历每个单项式,区分单个变量和多变量And两种情况,判断是否包含指定变量。

完整代码示例

基于你提供的代码扩展:

from sympy import symbols, Xor, And, Symbol
from sympy.logic.boolalg import to_anf

# 定义变量
a = symbols('a:{}'.format(2))
b = symbols('b:{}'.format(3))
c = symbols('c:{}'.format(1))

# 生成布尔表达式并转换为ANF
expr = ((a[0] & (~b[0])) ^ b[1]) & ((a[1] & (~b[2])) ^ c[0])
anf = expr.to_anf()

# 指定目标变量
target_var = c[0]

# 拆分ANF中的所有单项式
if isinstance(anf, Xor):
    monomials = anf.args
else:
    monomials = [anf]

# 筛选包含目标变量的单项式
filtered_monomials = []
for mono in monomials:
    if isinstance(mono, Symbol):
        if mono == target_var:
            filtered_monomials.append(mono)
    elif isinstance(mono, And):
        if target_var in mono.args:
            filtered_monomials.append(mono)

# 输出结果
print("包含{}的单项式:".format(target_var))
for mono in filtered_monomials:
    print(mono)

运行结果

针对示例中的ANF,输出为:

a0 & c0
b1 & c0
a0 & b0 & c0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:00:47