SymPy - Sets



In mathematics, a set is a well-defined collection of distinct objects which may be numbers, people, letters of the alphabet, or even other sets. Set is also one of the built-in types in Python. SymPy provides sets module. It contains definitions of different types of set and has functionality to perform set operations such as intersection, union, etc.

Set is a base class for any other type of set in SymPy. Note that it is different from built-in set data type of Python. Interval class represents real intervals and its boundary property returns a FiniteSet object.

>>> from sympy import Interval 
>>> s=Interval(1,10).boundary 
>>> type(s)

sympy.sets.sets.FiniteSet

FiniteSet is a collection of discrete numbers. It can be obtained from any sequence object such as list or string.

>>> from sympy import FiniteSet 
>>> FiniteSet(range(5))

Output

$\lbrace\lbrace0,1,...,4\rbrace\rbrace$

>>> numbers=[1,3,5,2,8] 
>>> FiniteSet(*numbers)

Output

$\lbrace1,2,3,5,8\rbrace$

>>> s="HelloWorld" 
>>> FiniteSet(*s)

Output

{H,W,d,e,l,o,r}

Note that, as in built-in set, SymPy's Set is also a collection of distinct objects.

ConditionSet is a set of elements that satisfy a given condition

>>> from sympy import ConditionSet, Eq, Symbol 
>>> x=Symbol('x') 
>>> s=ConditionSet(x, Eq(x**2-2*x,0), Interval(1,10)) >>> s

Output

$\lbrace x\mid x\in[1,10]∧x^2 - 2x =0\rbrace$

Union is a compound set. It includes all elements in two sets. Note that elements that are found in both, will appear only once in the Union.

>>> from sympy import Union 
>>> l1=[3,1,5,7] 
>>> l2=[9,7,2,1] 
>>> a=FiniteSet(*l1) 
>>> b=FiniteSet(*l2) 
>>> Union(a,b)

Intersection on the other hand contains only those elements that are present in both.

>>> from sympy import Intersection 
>>> Intersection(a,b)

ProductSet object represents Cartesian product of elements in both sets.

>>> from sympy import ProductSet 
>>> l1=[1,2] 
>>> l2=[2,3] 
>>> a=FiniteSet(*l1) 
>>> b=FiniteSet(*l2) 
>>> set(ProductSet(a,b))

Complement(a,b) retains elements in a excluding elements that are common with b set.

>>> from sympy import Complement 
>>> l1=[3,1,5,7] 
>>> l2=[9,7,2,1] 
>>> a=FiniteSet(*l1) 
>>> b=FiniteSet(*l2) 
>>> Complement(a,b), Complement(b,a)

SymmetricDifference set contains only uncommon elements in both sets.

>>> from sympy import SymmetricDifference 
>>> l1=[3,1,5,7] 
>>> l2=[9,7,2,1] 
>>> a=FiniteSet(*l1) 
>>> b=FiniteSet(*l2) 
>>> SymmetricDifference(a,b)

Output

{2,3,5,9}

Advertisements