Getting mutually disjoint subsets of a list

asked 2022-05-12 12:04:41 +0200

vidyarthi gravatar image

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.

edit retag flag offensive close merge delete

Comments

1

Use and instead of &. Also, you can replace set(i).intersection(set(j))==set() with set(i).isdisjoint(set(j)).

Max Alekseyev gravatar imageMax Alekseyev ( 2022-05-12 13:41:10 +0200 )edit

@MaxAlekseyev thanks! it works. But, why are the commands .intersection to be null and isdisjoint different?

vidyarthi gravatar imagevidyarthi ( 2022-05-12 14:17:55 +0200 )edit

The main issue was with using & (bitwise AND) rather than and (logical AND). Use of isjoint is optional here, it's just a bit nicer.

Max Alekseyev gravatar imageMax Alekseyev ( 2022-05-12 15:53:07 +0200 )edit