英文:
how do i have sympy yield `{1, 2}` given an positive integer `x < 3`
问题
我正在尝试使用 `sympy.solve` 解决一个不等式,以下是代码部分:
```python
from sympy import Symbol, solve
x = Symbol('x', positive=True, integer=True)
ineq1 = x - 3 < 0
solution = solve((ineq1), x)
print(solution)
上面的程序得到了 x < 3
的结果。虽然这个结果是合理的,但我想得到一个包含整数 1 和 2 的集合 {1, 2}
。
我该如何实现这一点?
<details>
<summary>英文:</summary>
I'm trying to solve an inequality using `sympy.solve`, here is the code
```python
from sympy import Symbol, solve
x = Symbol('x', positive=True, integer=True)
ineq1 = x - 3 < 0
solution = solve((ineq1), x)
print(solution)
The program above yields x < 3
. The result makes sense though, i'd like to get a set that consists of 2 integers 1 and 2, {1, 2}
.
how do i achieve that?
答案1
得分: 1
单变量不等式可以通过集合来处理,集合交集可以限制结果为正整数:
from sympy import Range, oo, S, And
ineq1.as_set().intersection(Range(1, oo))
{1, 2}
你也可以用S.Naturals
替代Range(1, oo)
。你还可以使用复合表达式,并将其集合与S.Integers
相交:
And(x > 0, x < 3).as_set().intersection(S.Integers)
{1, 2}
英文:
A univariate inequality can be handled by Sets and Set intersection can limit the result to positive integers:
>>> from sympy import Range, oo, S, And
...
>>> ineq1.as_set().intersection(Range(1,oo))
{1, 2}
You can also replace Range(1,oo)
with S.Naturals
. You can also use a compound expression and intersect its set with S.Integers
:
>>> And(x>0,x<3).as_set().intersection(S.Integers)
{1, 2}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论