Open In App

Python – Unique Tuple Frequency (Order Irrespective)

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

Given tuple list, extract the frequency of unique tuples in list order irrespective.

Input : test_list = [(3, 4), (1, 2), (4, 3), (3, 4)] 
Output : 2 
Explanation : (3, 4), (4, 3), (3, 4) makes 1 and (1, 2) is 2nd unique element. 
Input : test_list = [(3, 7), (1, 2), (4, 3), (5, 6)] 
Output : 4 
Explanation : All are different in any order.

Method #1 : Using tuple() + generator expression + sorted() + len() 

The combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sorted(), to remove order constraints. The len() is used to compute size. 

Python3




# Python3 code to demonstrate working of
# Unique Tuple Frequency [ Order Irrespective ]
# Using tuple() + list comprehension + sorted() + len()
 
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using tuple() + list comprehension + sorted() + len()
# Size computed after conversion to set
res = len(list(set(tuple(sorted(sub)) for sub in test_list)))
 
# printing result
print("Unique tuples Frequency : " + str(res))


Output : 

The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)]
Unique tuples Frequency : 3

Time Complexity: O(nlogn) where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list 

Method #2: Using map() + sorted() + tuple() + set() + len() 

The combination of the above functions can be used to solve this problem. In this, we perform the task of extending sorting logic and tuple conversion using map(), set() is used to eliminate duplicates and len() is used to find the length of the container. 

Python3




# Python3 code to demonstrate working of
# Unique Tuple Frequency [ Order Irrespective ]
# Using map() + sorted() + tuple() + set() + len()
 
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using map() + sorted() + tuple() + set() + len()
# inner map used to perform sort and outer sort to
# convert again in tuple format
res = len(list(set(map(tuple, map(sorted, test_list)))))
 
# printing result
print("Unique tuples Frequency : " + str(res))


Output : 

The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)]
Unique tuples Frequency : 3

Method#3: Using Recursive method.

This method works by recursively calling itself with the remaining elements of the input list after the first element is removed. It then checks if the first element is unique by comparing it to the sorted version of each of the remaining elements. If the first element is unique, it adds 1 to the frequency returned by the recursive call. If it is not unique, it simply returns the frequency returned by the recursive call. The base case is when the input list is empty, in which case the frequency is 0.

Python3




def unique_tuple_frequency(test_list):
   
    # base case
    if len(test_list) == 0:
        return 0
 
    # recursive call
    rest_freq = unique_tuple_frequency(test_list[1:])
 
    # check if the first element is unique
    for t in test_list[1:]:
        if sorted(test_list[0]) == sorted(t):
            return rest_freq
 
    # if the first element is unique, add 1 to the frequency
    return rest_freq + 1
 
 
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
 
# printing original list
print("The original list is :" + str(test_list))
 
# Using map() + sorted() + tuple() + set() + len()
# inner map used to perform sort and outer sort to
# convert again in tuple format
res = unique_tuple_frequency(test_list)
 
# printing result
print("Unique tuples Frequency : " + str(res))


Output

The original list is :[(3, 4), (1, 2), (4, 3), (5, 6)]
Unique tuples Frequency : 3

Time Complexity: O(N * MlogM)

Sorting each tuple: O(MlogM) where M is the size of the tuple.
Comparing each tuple to the first tuple: O(N * M) where N is the length of the input list and M is the size of the tuple.
Overall time complexity: O(N * MlogM)

Auxiliary Space: O(N * M)

Recursive call stack: O(N)
Creating a new list of remaining elements for each recursive call: O(N * M)

Method #4: Using dictionary and loop

Steps:

  1. Initialize an empty dictionary “freq_dict” to store the frequency of each unique tuple.
  2. Loop through each tuple in the input list “test_list”.
  3. Sort the tuple using sorted() and convert it to a tuple again using tuple(). This will give us a sorted version of the tuple, which we can use to check if it is unique.
  4. Check if the sorted tuple exists as a key in the “freq_dict”.
  5. If it does, increment the value of the corresponding key in “freq_dict”.
  6. If it does not, add the sorted tuple as a key to “freq_dict” with a value of 1.
  7. Finally, return the length of “freq_dict”, which will give us the number of unique tuples in “test_list”.

Python3




def unique_tuple_frequency(test_list):
   
    freq_dict = {}
    for tup in test_list:
        sorted_tup = tuple(sorted(tup))
        if sorted_tup in freq_dict:
            freq_dict[sorted_tup] += 1
        else:
            freq_dict[sorted_tup] = 1
    return len(freq_dict)
 
# Initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
 
# Printing original list
print("The original list is :" + str(test_list))
 
# Using dictionary and loop
res = unique_tuple_frequency(test_list)
 
# Printing result
print("Unique tuples Frequency : " + str(res))


Output

The original list is :[(3, 4), (1, 2), (4, 3), (5, 6)]
Unique tuples Frequency : 3

Time complexity: O(nlogn), where n is the length of the input list “test_list”.
Auxiliary space: O(n), where n is the length of the input list “test_list”. 



Similar Reads

Python - Tuple List intersection (Order irrespective)
Given list of tuples, perform tuple intersection of elements irrespective of their order. Input : test_list1 = [(3, 4), (5, 6)], test_list2 = [(5, 4), (4, 3)] Output : {(3, 4)} Explanation : (3, 4) and (4, 3) are common, hence intersection ( order irrespective). Input : test_list1 = [(3, 4), (5, 6)], test_list2 = [(5, 4), (4, 5)] Output : set() Exp
6 min read
Python | Extract unique tuples from list, Order Irrespective
Sometimes, while working with data, we can have a problem in which we need to check for similar records and eradicate them. When elements are ordered, this case has been discussed before. But sometimes, we might have to ignore the order and has to be removed in case similar elements occur. Let's discuss certain ways in which this task can be perfor
5 min read
Python Program to Remove duplicate tuples irrespective of order
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 rem
6 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
three90RightbarBannerImg