1

I have the following:

[[1, 2], [3], [4,5], [6,1], [5,3,4], [4,7]]

I'm trying to combine these so that if a number is in another array, I combine the arrays. The output should be this:

[[1,2,6],[3,4,5,7]]

Any ideas on how I can do this in Python?

myname
  • 1,337
  • 2
  • 11
  • 17

1 Answers1

0

Here's what I'd do:

>>> L = [[1, 2], [3], [4,5], [6,1], [5,3,4], [4,7]]
>>> L = [set(e) for e in L]
>>> combined = []
>>> while L:
...     group = L.pop()
...     for other in L:
...         if group.intersection(other):
...             group.update(other)
...     L = [e for e in L if not group.intersection(e)]
...     combined.append(group)
... 
>>> combined
[set([3, 4, 5, 7]), set([1, 2, 6])]

This first converts each group in the original list to set, then greedily merges the elements together into groups.

jterrace
  • 64,866
  • 22
  • 157
  • 202