I have a list of tuples. [ (1, 2), (2, 3), (4, 3), (5, 6), (6, 7), (8, 2) ]
I want to group them into lists based on which tuples are connected (have related values).
So the end result is two lists of related tuple values = [ [1, 2, 3, 4, 8], [5, 6, 7] ]
How can I write a function to do this? This was a job interview question. I was trying to do it in Python, but I'm frustrated and just want to see the logic behind the answer, so even psuedo code would help me, so I can see what I did wrong.
I only had a few minutes to do this on the spot, but here is what I tried:
def find_partitions(connections):
theBigList = [] # List of Lists
list1 = [] # The initial list to store lists
theBigList.append(list1)
for list in theBigList:
list.append(connection[1[0], 1[1]])
for i in connections:
if i[0] in list or i[1] in list:
list.append(i[0], i[1])
else:
newList = []
theBigList.append(newList)
Essentially, the guy wanted an list of lists of values that were related. I tried to use a for loop, but realized that it wouldn't work, and then time ran out.