Sympy Set Theory - How to reduce mathematical expressions?

77 Views Asked by At

Let's say I have n Sympy sets defined. The set sis:

s = FiniteSet('red', 'yellow', 'green')

Then I have three further sets:

a = FiniteSet('red')
b = FiniteSet('yellow')
c = FiniteSet('green')

It is obvious that a, b and c are subsets of s. When I let sympy calculate the Union of those three subsets, I would obtain the s But sympy gives as output:

>>>Union(a,b,c)
{'green', 'yellow', 'red'}

I would like to get s as a result.

Is there a way to achieve that with Sympy?

1

There are 1 best solutions below

0
smichr On

You might have to have a Gestalt Shift in your expectations. You are working in Python and you have assigned values to variables. Your expection is that when you print a variable d that has the same value as variable s that you will see the variable s -- but that's not what print(variable) does: it prints the value, not a list of any/all variables that are the same.

But you can ask SymPy if the two variables have the same values:

>>> d == s
True

You could also look through locals() (carefully) to find which name has the same value as d:

>>> L = locals()  # a dictionary of names and values
>>> [i for i in L if i != 'd' and type(L.get(i,None)) == type(d) and L[i] == d]
['s']

(But anything in locals that matches will be printed, not only s.)