Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a collection of sets is pairwise disjoint

What is the most efficient way to determine whether a collection of sets is pairwise disjoint? -- i.e. verifying that the intersection between all pairs of sets is empty. How efficiently can this be done?

like image 691
Robert T. McGibbon Avatar asked Mar 16 '14 04:03

Robert T. McGibbon


1 Answers

The sets from a collection are pairwise disjoint if, and only if, the size of their union equals the sum of their sizes (this statement applies to finite sets):

def pairwise_disjoint(sets) -> bool:
    union = set().union(*sets)
    return len(union) == sum(map(len, sets))

This could be a one-liner, but readability counts.

like image 83
Ioannis Filippidis Avatar answered Oct 14 '22 04:10

Ioannis Filippidis