Reputation: 129
I have an array like this:
array([[0, 1],
[0, 2],
[0, 4],
[2, 4],
[3, 4],
[5, 6]])
The connected values are defined as those who pair with each other, or with a shared value, for example, 1
and 2
are connected because they pair with the same value 0
.
So the output I wanna get is like this (any data type will do):
{0,1,2,3,4}, {5,6}
.
TIA.
Upvotes: 0
Views: 344
Reputation: 147146
One way to do this would be to create a list of sets, and add values from the list into the sets based on overlap with existing values in the set; if there is no overlap, pushing a new set into the list:
def group_values(vals):
def group_val(vals):
sets = []
for val in vals:
for s in sets:
if any(v in s for v in val):
s.update(val)
break
else:
sets.append(set(val))
return sets
sets = group_val(vals)
# check if any more merging is required
newsets = group_val(sets)
while len(newsets) != len(sets):
sets = newsets
newsets = group_val(sets)
return sets
vals = [[0, 1], [0, 2], [0, 4], [2, 4], [3, 4], [5, 6]]
print([s for s in group_values(vals)])
vals = [[0, 1], [0, 2], [0, 4], [2, 4], [3, 4], [5, 6], [8, 6], [7, 4], [7, 6], [7, 8]]
print([s for s in group_values(vals)])
Output:
[{0, 1, 2, 3, 4}, {5, 6}]
[{0, 1, 2, 3, 4, 5, 6, 7, 8}]
Upvotes: 2