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

使用SymPy求解含非负整数变量的二元不等式问题

用SymPy求解非负整数的不等式解列表

需求是找出所有满足0 < x + y ≤ 4的非负整数(x,y)元组,预期结果为:

[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (4, 0)]

原代码问题

原代码尝试用SymPy的solve函数直接求解,但SymPy的solve对于带整数约束的不等式,返回的是符号形式的解区间,而非具体的元组列表。原代码如下:

import sympy as sp

# Assign variables
x, y = sp.symbols('x y', natural0 = True)

# Define the inequalities
ineq1 = sp.And(0 < x + y, x + y <= 4)
ineq2 = x >= 0
ineq3 = y >= 0

# Solve the inequality
result = sp.solve([ineq1, ineq2, ineq3], [x,y])

运行后result会得到符号化的解范围,无法直接得到预期的元组列表。

解决方案

方法1:结合SymPy枚举整数解

利用SymPy求解x的范围,再遍历每个x值计算对应的y范围,收集所有符合条件的元组:

import sympy as sp

x, y = sp.symbols('x y', natural0=True)

# 获取x的取值范围
x_range = sp.solve(sp.And(x >= 0, x <= 4), x)
solutions = []

# 遍历每个x的整数取值
for x_val in range(x_range.lhs, x_range.rhs + 1):
    # 求解对应x下y的约束条件
    y_conditions = sp.And(y >= 0, y <= 4 - x_val, x_val + y > 0)
    y_range = sp.solve(y_conditions, y)
    # 遍历y的整数取值并收集解
    for y_val in range(y_range.lhs, y_range.rhs + 1):
        solutions.append((x_val, y_val))

print(solutions)

方法2:直接枚举(更简洁)

由于取值范围很小,直接通过列表推导式枚举所有非负整数对,筛选符合条件的解:

solutions = [(x, y) for x in range(5) for y in range(5) if 0 < x + y <= 4]
print(solutions)

两种方法都能输出预期的元组列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:16:06