Emilien
Emilien

Reputation: 2445

Sympy relational symbol in set

I have a FiniteSet and a symbol with which I want to associate a Relation such that the symbol is in the FiniteSet, is it possible with sympy? symbol in FiniteSet does not return an expression, but instead evaluates it:

>>> from sympy import *   
>>> s = FiniteSet(range(0,3))
>>> x = symbols('x')
>>> x in s
False
>>> Eq(x,s)
x == {0, 1, 2}
>>> In(x,s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'In' is not defined

Edit: Thanks to ohe for telling me about Contains. I updated my version of sympy, by the way the syntax of FinitSet also changed in the update. I give the small example that I expected to work in the first place for the record:

>>> from sympy import *   
>>> x = symbols('x')
>>> s = FiniteSet(*range(0,3))
>>> init_printing()
>>> Contains(x,s)
x ∈ {0, 1, 2}

Upvotes: 1

Views: 732

Answers (2)

lhk
lhk

Reputation: 30046

Your code doesn't work for me. The expression

x in s

raises an exception. You have to assign a value to x first. Then you can just use "in".

Like this:

s = FiniteSet(range(0,3))
x = symbols('x')
x=3
x in s # False

Here is the complete setup:

>>> from sympy import *
>>> s=FiniteSet(range(0,3))
>>> x=symbols("x")
>>> x in s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\lhk\Anaconda3\lib\site-packages\sympy\sets\sets.py", line 497, in __contains__
    raise TypeError('contains did not evaluate to a bool: %r' % symb)
TypeError: contains did not evaluate to a bool: Contains(x, {range(0, 3)})
>>> x=3
>>> x in s
False
>>> Contains(x,s)
False
>>>

Upvotes: 0

ohe
ohe

Reputation: 3673

What you're looking for might be the Contains function.

Upvotes: 2

Related Questions