Sympy intersection of FiniteSets with strings

117 Views Asked by At

Define two sympy FiniteSet sets a and b with each of them containing only one string element:

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

If I ask for the Intersection of those sets:

Intersection(a,b)

I was expecting to get as result an empty set {}, but I just get Intersection({red}, {yellow}). Why is that?

It works well for Union:

Union(a,b) = {'red', 'yellow'}. 

Even if I define those sets:

a = FiniteSet('red', 'yellow')
b = FiniteSet('red')

I get the expected result: Intersection(a,b) = {'red'}.

I was planing to use those set manipulations to reduce/simplify rather long symbolic representations of combinations of different sets. But with this behavior it will not work.

It also works well with the built-in python sets:

a = {'red'}
b = {'yellow'}
a.intersection(b)

leads to set(). Is this a bug in sympy?

1

There are 1 best solutions below

4
smichr On

The intersection cannot unambiguously give a result for objects which are variables. Your strings became Symbols with color names and a might equal b or it might not. If your elements were 'a+1' and 'a+2' the intersection would be an empty set because those two cannot be the same for finite values.

If you intend that distinct items are distinct, then map them to integers, allow simplification to take place, and then map them back to symbols:

reps = {s:i for i, s in expr.atoms(Symbol)}
expr = expr.xreplace(reps).xreplace({i:s for s,i in reps.items()})