Given the two sets to compare against
waters = frozenset(['tea', 'lemonade', 'juice', 'pepsi'])
oils = frozenset(['olive oil', 'corn oil', 'peanut oil'])
And a test group
foo = frozenset(['tea', 'corn oil'])
You can determine if the set contains items from exclusively one group (using the XOR operator) by checking if the sets are disjoint (two sets are disjoint if their intersection is the empty set).
foo.isdisjoint(waters) ^ foo.isdisjoint(oils)
For Python 2.5 and older, use:
bool(foo.intersection(waters)) ^ bool(foo.intersection(oils))
Alternatively, if you can remember that &
is the intersection operator when acting on two sets. Because readability counts, if you or other people who are (or will be) maintaining your code aren't sure what the &
character means without looking it up, just use s1.intersection(s2)
.
bool(foo & waters) ^ bool(foo & oils)