I am trying to pair elements of a list based on a condition.
If two element have a common i will merge them and do this until no elements can be merged. Currently, my problem is looping through same elements and getting same merged result from different items. I have to check if group has been added before.But as my array is empty in the beginning i could not check if element already in it with axis 1. I tried recursive : Also i am discarding if a group has length less than three.
pairs = [[1, 3], [1, 8], [2, 1], [2, 3], [3, 1], [3, 8], [4, 11], [4, 15], [7, 13], [9, 12], [9, 13], [10, 1], [10, 18], [10, 20], ...]
def groupG(pairs):
groups = []
if len(pairs) > 1:
for i,pair in enumerate(pairs):
try:
if (any(point in pairs[i+1] for point in pair)):
group = np.concatenate(( pair,pairs[i+1]))
group = np.unique(group)
groups.append(group)
except IndexError:
continue
if len(groups) == 0 :
groupsFiltered = np.array([row for row in pairs if len(row)>=3])
return groupsFiltered
else:
return groupG(groups)
expected result is :
[[1,2,3,8,10,18,20],[4,11,15],[7,9,12,13]...]
Is there a way to group these pairs with while,do while or recursive?