Sympy如何在给定正整数`x < 3`时生成`{1, 2}`?

huangapple go评论54阅读模式
英文:

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&#39;m trying to solve an inequality using `sympy.solve`, here is the code
```python
from sympy import Symbol, solve
x = Symbol(&#39;x&#39;, positive=True, integer=True)
ineq1 = x - 3 &lt; 0
solution = solve((ineq1), x)
print(solution)

The program above yields x &lt; 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:

&gt;&gt;&gt; from sympy import Range, oo, S, And
...
&gt;&gt;&gt; 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:

&gt;&gt;&gt; And(x&gt;0,x&lt;3).as_set().intersection(S.Integers)
{1, 2}

huangapple
  • 本文由 发表于 2023年6月1日 07:11:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377801.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定