Given a list:
g = [[0, 7],
[1, 2, 10, 19],
[3, 4, 5, 6, 15, 21, 24, 27],
[0, 7, 8, 9, 12, 17],
[1, 10, 11, 20],
[8, 12, 13, 18],
[14, 25],
[3, 15, 16, 22],
[9, 13, 17, 18]]
I want to check the numbers in the sublist so that for any number that exists in more than one sublist, both sublists can combine to form a new list, e.g. [8, 12, 13, 18]
and [9, 13 ,17, 18]
can combine to give [8, 9, 12, 13, 17, 18]
. Note: the number doesn't repeat and I want to make the biggest possible list.
I have written the following code, but it is not perfect and repeat has not be eliminated, can anyone help?
for i in g:
for j in g:
for k in i:
for l in j:
if k == l:
m=list(set(i + j))
if m not in n:
n.append(m)
My expected output is:
[[0, 7, 8, 9, 12, 13, 17, 18],
[1, 2, 10, 11, 19, 20],
[3, 4, 5, 6, 15, 16, 21, 22, 24, 27],
[25, 14]]