Getting mutually disjoint subsets of a list
Consider the following code:
import itertools
m=[]
l=[[1,2],[1,3],[3,4],[5,6],[1,4]]
for i,j,k in itertools.combinations(l,3):
if set(i).intersection(set(j))==set() & set(i).intersection(set(k))==set() & set(j).intersection(set(k))==set():
m.append((i,j,k))
m
Why am i getting the output
[([1, 2], [3, 4], [5, 6]),
([1, 2], [3, 4], [1, 4]),
([1, 2], [5, 6], [1, 4]),
([1, 3], [5, 6], [1, 4]),
([3, 4], [5, 6], [1, 4])]
when the expected output is
[[1,2],[3,4],[5,6]]
How do I rectify the code to get my desired output. I want the subsets that mutually disjoint from each other. Any hints? Thanks beforehand.
Use
and
instead of&
. Also, you can replaceset(i).intersection(set(j))==set()
withset(i).isdisjoint(set(j))
.@MaxAlekseyev thanks! it works. But, why are the commands
.intersection
to be null andisdisjoint
different?The main issue was with using
&
(bitwise AND) rather thanand
(logical AND). Use ofisjoint
is optional here, it's just a bit nicer.