I am looking for a fast method to traverse a list of sets, and to expand each set by finding its union with any other element of the list with which it shares at least one element.
For example, suppose that I have four rows of data, where each row corresponds to a set of unique elements
0, 5, 101
8, 9, 19, 21
78, 79
5, 7, 63, 64
The first and the last rows have the intersecting element 5 and so after performing my operation I want to have the unions
0, 5, 7, 63, 64, 101
8, 9, 19, 21
78, 79
0, 5, 7, 63, 64, 101
Right now, I can nearly do this with two loops:
def consolidate_list(arr):
"""
arr (list) : A list of lists, where the inner lists correspond to sets of unique integers
"""
arr_out = list()
for item1 in arr:
item_additional = list() # a list containing all overlapping elements
for item2 in arr:
if len(np.intersect1d(item1, item2)) > 0:
item_additional.append(np.copy(item2))
out_val = np.unique(np.hstack([np.copy(item1)] + item_additional)) # find union of all lists
arr_out.append(out_val)
return arr_out
The issue with this approach is that it needs to be run multiple times, until the output stops changing. Since the input might be jagged (ie, different numbers of elements per set), I can't see a way to vectorize this function.