Given a list of binary tuples, the task is to write a Python program to remove all tuples that are duplicates irrespective of order, i.e delete if contains similar elements, irrespective of order.
Input : test_list = [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
Output : [(1, 2), (5, 7), (4, 6), (2, 9)]
Explanation : (2, 1), (6, 4) are removed as (1, 2), (4, 6) are already included.
Input : test_list = [(4, 7), (1, 2), (9, 2), (2, 1), (5, 7), (7, 4), (9, 2)]
Output : [(1, 2), (5, 7), (4, 7), (2, 9)]
Explanation : (2, 1), (7, 4) are removed as (1, 2), (4, 7) are already included.
In this, we sort each element of tuple using sorted() and map(). Then result is converted to set to remove duplicates. At last, set is converted to list.
OutputThe original list is : [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
Tuples after removal : [(1, 2), (5, 7), (4, 6), (2, 9)]
This is a naive approach for the required solution. In this, each element of list is sorted using list comprehension and sorted(), then result is converted back to remove duplicates using set().
OutputThe original list is : [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
Tuples after removal : [(1, 2), (5, 7), (4, 6), (2, 9)]
The function remove_duplicates takes in the test_list, an optional index (default value is 0), and a res set (default value is an empty set).
At each recursive call, the function checks if the index has reached the end of the test_list. If it has, then it returns the res set as a list.
If the index has not reached the end of the test_list, then the function adds the sorted tuple at the index to the res set.
The function then calls itself recursively with the index incremented by 1 and the res set passed along.
OutputThe original list is : [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
Tuples after removal : [(1, 2), (5, 7), (4, 6), (2, 9)]
The idea is to use the re-module to remove duplicate tuples irrespective of order. It first converts each tuple to a string by sorting it and then converting it to a string using str(). It then sorts the resulting list of strings. Next, it uses regular expressions to remove duplicates from the sorted list. It converts the sorted list to a set to remove duplicates and then converts it back to a list. Finally, it converts each string in the unique list back to a tuple using eval(), which evaluates the string as a Python expression.
OutputOriginal list: [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
Tuples after removal: [(1, 2), (2, 9), (4, 6), (5, 7)]