Is there any effective way to merge sets which have intersections. For example:
l = [{1, 3}, {2, 3}, {4, 5}, {6, 5}, {7, 5}, {8, 9}]
The expected result is:
r = [{1, 2, 3}, {4, 5, 6, 7}, {8, 9}]
All sets which have intersection (common components) should be merged. For example:
{1, 3} & {2, 3}
# {3}
So these two sets should be merged:
{1, 3} | {2, 3}
# {1, 2, 3}
Unfortunately I don't have any working solution.
UPDATE: The order of sets in the result is not important.
An efficient way to implement the connected components algorithm as mentioned by @mkrieger1 in the comments is to convert the list of sets to a set of hashable frozensets so that as you iterate through it and find a frozenset that intersects with the current one you can easily remove it from the pool:
Given
l = [{1, 3}, {2, 3}, {4, 5}, {6, 5}, {7, 5}, {8, 9}]
,groups
will become:And given
l = [{1, 2}, {3, 4}, {2, 3}]
,groups
will become:And given
l = [{1}, {2}, {1, 2}]
,groups
will become:I propose this solution:
The test cases this works for:
Does this work for you?