The graph approach is likely faster than recursion, but for those interested in pure Python:
def get_disjoints(lst):
"""Return disjoints."""
def rec_disjoints(lst):
if not lst:
return disjoints
else:
chosen = lst[0]
# Iterat/Mutate list trick using indicies
for i, s in reversed(list(enumerate(lst[:]))):
if not chosen.isdisjoint(s):
chosen.update(s)
del lst[i]
disjoints.append(chosen)
return rec_disjoints(lst)
disjoints = []
return rec_disjoints(lst)
lst = [{1,2}, {2,3}, {4,5}, {5,6}, {1,7}]
get_disjoints(lst)
# [{1, 2, 3, 7}, {4, 5, 6}]
This takes advantage of the helpful isdisjoint method for sets. Although, iteration + function calls + recursion will reduce performance.
Here are tests for robustness, applicable for other contributors:
import nose.tools as nt
def test_disjoint(f):
"Verify the test function generates expected disjoints."
def verify(lst1, lst2):
actual, expected = lst1, lst2
nt.eq_(actual, expected)
verify(f([{1,2}, {2,3}, {4,5}, {5,6}, {1,7}]),
[{1,2,3,7}, {4,5,6}])
verify(f([{4,5}, {5,6}, {1,7}]),
[{4,5,6}, {1,7}])
verify(f([{1,7}]),
[{1,7}])
verify(f([{1,2}, {2,3}, {4,5}, {5,6}, {1,7}, {10, 11}]),
[{1,2,3,7}, {4,5,6}, {10,11}])
verify(f([{4,5}, {5,6}, {1,7}, {10, 11}]),
[{4,5,6}, {1,7}, {10,11}])
verify(f([{1,2}, {4,5}, {6,7}]),
[{1,2}, {4,5}, {6,7}])
test_disjoint(f=get_disjoints)