Open In App

Python | Unique pairs in list

Last Updated : 09 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with python list, we can have a binary matrix ( Nested list having 2 elements ). And we can have a problem in which we need to find the uniqueness of a pair. A pair is unique irrespective of order, it doesn’t appear again in list. Let’s discuss certain way in which this task can be performed. 

Method 1: Using frozenset() + Counter() + list comprehension The combination of above functions can perform this task. The frozenset() is used for ignoring the ordering, Counter() is used to perform the task of checking the uniqueness and iteration is done using list comprehension. 

Python3




# Python3 code to demonstrate working of
# Unique pairs in list
# using frozenset() + Counter() + list comprehension
from collections import Counter
 
# initialize list
test_list = [[5, 6], [9, 8], [8, 9], [1, 4], [6, 5], [10, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Unique pairs in list
# using frozenset() + Counter() + list comprehension
temp = Counter(frozenset(ele) for ele in test_list)
res = [temp[frozenset(ele)] == 1 for ele in test_list]
 
# printing result
print("The Unique status of elements is " + str(res))


Time Complexity: O(n*n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method#2: using a dictionary

Approach

This approach uses a dictionary to keep track of unique pairs. It first sorts each pair and converts it to a tuple to ensure that pairs with the same elements are represented in the same way. It then checks if the tuple is already a key in the dictionary. If it is, it marks the pair as not unique by setting the corresponding value to False. If the tuple is not a key in the dictionary, it adds the tuple as a key to the dictionary with the value set to True, indicating that the pair is unique. Once the dictionary is populated, the approach iterates over the list of pairs again and for each pair, it sorts the pair and converts it to a tuple. It then retrieves the value associated with the tuple in the dictionary and appends it to the list of unique statuses. This generates the final list of unique statuses corresponding to each pair in the original list.

Algorithm

1. Create an empty dictionary called “pair_dict”.
2. Iterate over the list of pairs and for each pair:
a. Sort the pair.
b. Convert the sorted pair to a tuple.
c. If the tuple is already a key in the dictionary, mark the pair as not unique by setting the corresponding value to False.
d. If the tuple is not a key in the dictionary, add the tuple as a key to the dictionary with the value set to True.
3. Iterate over the list of pairs and for each pair:
a. Sort the pair.
b. Convert the sorted pair to a tuple.
c. Retrieve the value associated with the tuple in the dictionary and append it to the list of unique statuses.
4. Return the list of unique statuses.

Python3




def find_unique_pairs(lst):
    pair_dict = {}
    unique_statuses = []
    for pair in lst:
        sorted_pair = sorted(pair)
        tup = tuple(sorted_pair)
        if tup in pair_dict:
            pair_dict[tup] = False
        else:
            pair_dict[tup] = True
    for pair in lst:
        sorted_pair = sorted(pair)
        tup = tuple(sorted_pair)
        unique_statuses.append(pair_dict[tup])
    return unique_statuses
 
lst = [[5, 6], [9, 8], [8, 9], [1, 4], [6, 5], [10, 1]]
print(find_unique_pairs(lst))


Output

[False, False, False, True, False, True]

Time Complexity: O(n log n), where n is the number of pairs in the list. This is due to the sorting operation that is performed for each pair. Retrieving a value from a dictionary takes constant time on average, so the second loop has a time complexity of O(n).
Auxiliary Space: O(n), where n is the number of pairs in the list. The dictionary may have at most n keys, and the list of unique statuses also has a length of n.

Method#3: Using itertools:

Algorithm:

  1. Create an empty set named unique_pairs to store the unique pairs.
  2. Use itertools.combinations() to generate all possible pairs of the input list.
  3. For each pair generated in step 2, sort each element of the pair and check if both sorted pairs are equal.
  4. If both sorted pairs are equal, add each of the original pairs to the unique_pairs set.
  5. Create a list named unique_statuses and iterate over the original list.
  6. Check if each pair in the original list is in the unique_pairs set.
  7. Append True if the pair is unique and False if it is not.
  8. Return the unique_statuses list.

Python3




import itertools
 
def find_unique_pairs(lst):
    unique_pairs = set()
    for pair in itertools.combinations(lst, 2):
        if sorted(pair[0]) == sorted(pair[1]):
            unique_pairs.add(tuple(pair[0]))
            unique_pairs.add(tuple(pair[1]))
    unique_statuses = [tuple(pair) not in unique_pairs for pair in lst]
    return unique_statuses
 
lst = [[5, 6], [9, 8], [8, 9], [1, 4], [6, 5], [10, 1]]
  
# printing original list
print("The original list is : " + str(lst))
  
print(find_unique_pairs(lst))
#This code  is contribute by Jyothi pinjala.


Output

The original list is : [[5, 6], [9, 8], [8, 9], [1, 4], [6, 5], [10, 1]]
[False, False, False, True, False, True]

Time complexity: The time complexity of this algorithm is O(n^2), where n is the length of the input list. This is due to the nested loops used in the itertools.combinations() method.
Auxiliary Space: The space complexity of this algorithm is also O(n^2), because in the worst case scenario, all possible pairs will be stored in the unique_pairs set.

Method 4 : use a nested loop and compare each pair of sublists, and keep track of unique pairs using a set.  

step-by-step approach:

  • Initialize an empty set to store unique pairs.
  • Initialize an empty list to store the unique statuses of each pair.
  • Use a nested loop to compare each pair of sublists.
  • Check if the pair is unique by comparing the sorted elements of each sublist.
  • If the pair is unique, add it to the set of unique pairs.
  • Use a list comprehension to check if each pair in the input list is unique, and store the result in the list of unique statuses.
  • Return the list of unique statuses.

Python3




def find_unique_pairs(lst):
    unique_pairs = set()
    unique_statuses = []
    for i in range(len(lst)):
        for j in range(i+1, len(lst)):
            if sorted(lst[i]) == sorted(lst[j]):
                unique_pairs.add(tuple(lst[i]))
                unique_pairs.add(tuple(lst[j]))
    unique_statuses = [tuple(pair) not in unique_pairs for pair in lst]
    return unique_statuses
 
lst = [[5, 6], [9, 8], [8, 9], [1, 4], [6, 5], [10, 1]]
 
# printing original list
print("The original list is : " + str(lst))
 
print(find_unique_pairs(lst))


Output

The original list is : [[5, 6], [9, 8], [8, 9], [1, 4], [6, 5], [10, 1]]
[False, False, False, True, False, True]

Time complexity: O(n^2) where n is the length of the input list because of the nested loop.
Auxiliary space: O(n) to store the set of unique pairs and the list of unique statuses.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads