siddharth
siddharth

Reputation: 300

How do i find all the elements in a list of tuples that are same in python?

I Have a list of tuples, each tuple contains 2 integer. eg. [(1, 2), (2, 3), (3, 4), (4, 5), (100, 130), (130, 140), (140, 150), (150, 170)]

How do I find the elements that are same? Here, in this example 1 and 2 are same; 2 and 3 are same; so 1 and 3 are also same. The answer to the above example would be :

1,2,3,4,5

100,130,140,150,170

I would prefer if the answer is a list of lists, but any solution that works is fine.

Upvotes: 0

Views: 266

Answers (3)

Edwin van Mierlo
Edwin van Mierlo

Reputation: 2488

Not very clear from the question how you like the result.

You do mention you want a list of lists, but does not specify what the criteria are for creating this.

If you update your question with what the criteria are to split the result in multiple lists, to create your list of lists, I will try to update this answer

Here is a one-liner to produce one single list as result.

given:

tuples_v = [(1, 2), (2, 3), (3, 4), (4, 5), (100, 130), (130, 140), (140, 150), (150, 170)]

result:

result = list(set([value_v for tuple_v in tuples_v for value_v in tuple_v]))

Upvotes: 0

Mia
Mia

Reputation: 2676

David Z provided an excellent solution to solve more complicated problems similar to yours. But I understand your question correctly, David Z's answer is a little bit overkill for your question. You do not need to define any new classes or data structures.

I think what you need to do is simply put every number you have into a set. Because a set cannot have any duplicated elements, this process actually finds the same elements. As in the code below:

list_of_tuples=[(1, 2), (2, 3), (3, 4), (4, 5), (100, 130), (130, 140), (140, 150), (150, 170)]
ans=set()
for t in list_of_tuples:
    for num in t:
        ans.add(num)
print(list(ans))

Upvotes: 0

David Z
David Z

Reputation: 131610

Assuming that an element's position within a tuple doesn't matter (so e.g. it wouldn't make a difference if you had (2, 1) in place of (1, 2)), I think what you need is the disjoint-set merge, also known as "union-find". Basically, you could iterate over your tuples

for t1, t2 in list_of_tuples:

and for each one, make a set in the data structure corresponding to each of the elements if it doesn't already exist

    disjoint_set_structure.make_set(t1)
    disjoint_set_structure.make_set(t2)

then unify the two sets

    disjoint_set_structure.union(t1, t2)

At the end you would be able to get the distinct groups from disjoint_set_structure, if your implementation supports it.

There are many implementations of the disjoint-set data structure available online, and you can also create your own fairly easily in probably about 50 lines of code.

Upvotes: 1

Related Questions