Find Numeric Subset Groups
Suppose I have these numeric sets
a = {1, 2, 3}
b = {2, 3, 4}
c = {1, 5}
I want to find all the different numeric groupings of sets. The result will be
{1}, {2, 3}, {4}, {5}
My naive approach that doesn't work looks something like this:
data = [{1, 2, 3}, {2, 3, 4}, {1, 5}]
for i in range(1, 5):
s = set.intersection(*[x for x in data if i in x])
print(s)
What returns
set([1])
set([2, 3])
set([2, 3])
set([2, 3, 4])
Which can be easily removed but does not give the expected result.
How can I get only groups of numbers that exist in a subset of the sets?
+3
source to share
1 answer
There are two problems in your code:
- You stop at
5
butrange
does not include the stop, so you do not check 5. - If the value is in only one set, then you need to create a set containing only that value. At the very least, your expected result looks like this is the desired behavior.
So, after fixing these problems, the code will look like this:
data = [{1, 2, 3}, {2, 3, 4}, {1, 5}]
for i in range(1, 6):
useful_sets = [x for x in data if i in x]
if len(useful_sets) <= 1:
print(set([i]))
else:
s = set.intersection(*useful_sets)
print(s)
# prints:
# {1}
# {2, 3}
# {2, 3}
# {4}
# {5}
To get a complete (and not duplicated) result, you can save them as freeze-created in a set:
data = [{1, 2, 3}, {2, 3, 4}, {1, 5}]
res = set()
for i in range(1, 6):
useful_sets = [x for x in data if i in x]
if len(useful_sets) <= 1:
res.add(frozenset([i]))
else:
s = set.intersection(*useful_sets)
res.add(frozenset(s))
print(res)
# {frozenset({5}), frozenset({4}), frozenset({2, 3}), frozenset({1})}
Which (with the exception of the order) should be exactly what you want.
+5
source to share