Python – Assign Frequency to Tuples
Last Updated :
02 May, 2023
Given tuple list, assign frequency to each tuple in list.
Input : test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (9, ), (2, 7)]
Output : [(6, 5, 8, 2), (2, 7, 2), (9, 1)]
Explanation : (2, 7) occurs 2 times, hence 2 is append in tuple.
Input : test_list = [(2, 7), (2, 7), (6, 5, 8), (9, ), (2, 7)]
Output : [(6, 5, 8, 1), (2, 7, 3), (9, 1)]
Explanation : (2, 7) occurs 3 times, hence 3 is append in tuple.
Method #1 : Using Counter() + items() + * operator + list comprehension
In this, we extract the frequency using Counter(), fetch frequency numbers using items(), * operator is used to unpack elements and list comprehension is used to assign this to all elements in tuple list.
Python3
from collections import Counter
test_list = [( 6 , 5 , 8 ), ( 2 , 7 ), ( 6 , 5 , 8 ), ( 6 , 5 , 8 ), ( 9 , ), ( 2 , 7 )]
print ( "The original list is : " + str (test_list))
res = [( * key, val) for key, val in Counter(test_list).items()]
print ( "Frequency Tuple list : " + str (res))
|
Output
The original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Method #2 : Using most_common() + Counter() + * operator + list comprehension
This is similar to the above method, just most_common() performs sort operation on list, which is not necessary.
Python3
from collections import Counter
test_list = [( 6 , 5 , 8 ), ( 2 , 7 ), ( 6 , 5 , 8 ), ( 6 , 5 , 8 ), ( 9 , ), ( 2 , 7 )]
print ( "The original list is : " + str (test_list))
res = [( * key, val) for key, val in Counter(test_list).most_common()]
print ( "Frequency Tuple list : " + str (res))
|
Output
The original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Method #3 : Using count(),list(),tuple() methods
Python3
test_list = [( 6 , 5 , 8 ), ( 2 , 7 ), ( 6 , 5 , 8 ), ( 6 , 5 , 8 ), ( 9 , ), ( 2 , 7 )]
print ( "The original list is : " + str (test_list))
res = []
for i in test_list:
if i not in res:
res.append(i)
res1 = []
for i in res:
x = list (i)
x.append(test_list.count(i))
p = tuple (x)
res1.append(p)
print ( "Frequency Tuple list : " + str (res1))
|
Output
The original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Method #4 : Using operator.countOf(),list(),tuple() methods
Python3
import operator as op
test_list = [( 6 , 5 , 8 ), ( 2 , 7 ), ( 6 , 5 , 8 ), ( 6 , 5 , 8 ), ( 9 , ), ( 2 , 7 )]
print ( "The original list is : " + str (test_list))
res = []
for i in test_list:
if i not in res:
res.append(i)
res1 = []
for i in res:
x = list (i)
x.append(op.countOf(test_list,i))
p = tuple (x)
res1.append(p)
print ( "Frequency Tuple list : " + str (res1))
|
Output
The original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Time Complexity: O(N*N), where n is the length of the given tuple
Auxiliary Space: O(N*N)
METHOD 5:Using dictionary and list comprehension: The method returns the value for a key if it exists in the dictionary, otherwise it returns a default value of 0. This allows us to simplify the if-else statement in the for a loop. The rest of the solution is the same as before, creating a list of tuples using list comprehension.
- Create an empty dictionary to store the frequencies of each tuple.
- Iterate over each tuple in the given list and add it to the dictionary if it doesn’t exist, with a frequency of 1. If the tuple already exists, increment its frequency by 1.
- Use a list comprehension to create a new list of tuples with the original tuples and their frequencies.
Python3
def assign_frequency(lst):
freq_dict = {}
for tup in lst:
if tup in freq_dict:
freq_dict[tup] + = 1
else :
freq_dict[tup] = 1
return [(key + (value,)) for key, value in freq_dict.items()]
lst = [( 6 , 5 , 8 ), ( 2 , 7 ), ( 6 , 5 , 8 ), ( 6 , 5 , 8 ), ( 9 , ), ( 2 , 7 )]
print (assign_frequency(lst))
|
Output
[(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Time Complexity: O(n) where n is the number of tuples in the list.
Space Complexity: O(n) since the dictionary stores the frequencies of each tuple.
METHOD 6:Using reduce():
Algorithm:
- Import Counter and reduce from their respective modules.
- Initialize the original list test_list.
- Print the original list.
- Use reduce to merge all the tuples in the list into a single Counter object that counts the frequency of each tuple.
- Create a list of tuples by iterating over the Counter object, unpacking each tuple into the tuple elements and frequency.
- Sort the list of tuples in descending order of frequency.
- Print the final list.
Python3
from collections import Counter
from functools import reduce
test_list = [( 6 , 5 , 8 ), ( 2 , 7 ), ( 6 , 5 , 8 ), ( 6 , 5 , 8 ), ( 9 , ), ( 2 , 7 )]
print ( "The original list is : " + str (test_list))
res = reduce ( lambda x, y: x + y, [Counter([t]) for t in test_list])
res = [( * key, val) for key, val in res.items()]
res.sort(key = lambda x: x[ - 1 ], reverse = True )
print ( "Frequency Tuple list : " + str (res))
|
Output
The original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
Time complexity: O(n log n), where n is the length of the original list. This is because sorting the list of tuples takes O(n log n) time.
Space complexity: O(n), where n is the length of the original list. This is because we create a new list of tuples with the same length as the original list. The Counter object also takes O(n) space.
METHOD 7:Using groupby():
Algorithm:
- Create an empty dictionary, freq_dict.
- For each element in the list, do the following:
a. Check if the element is already in the dictionary.
b. If it is not in the dictionary, add it with a value of 1.
c. If it is in the dictionary, increment its value by 1.
- Create an empty list, freq_list.
- For each key-value pair in the dictionary, create a tuple (key, value) and append it to the freq_list.
- Sort the freq_list in ascending order based on the second element (frequency).
- Return the freq_list.
Python3
import itertools
test_list = [( 6 , 5 , 8 ), ( 2 , 7 ), ( 6 , 5 , 8 ), ( 6 , 5 , 8 ), ( 9 , ), ( 2 , 7 )]
print ( "The original list is : " + str (test_list))
res = []
for row, group in itertools.groupby( sorted (test_list)):
count = sum ( 1 for _ in group)
res.append(row + (count,))
print ( "Frequency Tuple list : " + str (res))
|
Output
The original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9,), (2, 7)]
Frequency Tuple list : [(2, 7, 2), (6, 5, 8, 3), (9, 1)]
Time complexity:
The time complexity of this algorithm is O(n log n), where n is the length of the input list. This is because the algorithm involves iterating through the input list once (O(n)), adding and updating dictionary elements (which has an average case time complexity of O(1)), creating a new list of tuples (O(n)), and sorting that list using Python’s built-in sorted function (which has a time complexity of O(n log n)).
Auxiliary Space:
The space complexity of this algorithm is O(n), where n is the length of the input list. This is because the algorithm creates a dictionary with up to n unique elements, a list with n elements, and several temporary variables (which have a constant space complexity).
Similar Reads
Python - Elements frequency in Tuple
Given a Tuple, find the frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on.. Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using def
7 min read
Python | Tuple Column element frequency
In Python, we need to handle various forms of data and one among them is a list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the Kth element in the list of tuples. Letâs discuss certain ways in which this can
5 min read
Python | Finding frequency in list of tuples
In python we need to handle various forms of data and one among them is list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the 1st element in list of tuple which can be extended to any index. Let's discuss cert
6 min read
Creating Sets of Tuples in Python
Tuples are an essential data structure in Python, providing a way to store ordered and immutable sequences of elements. When combined with sets, which are unordered collections of unique elements, you can create powerful and efficient data structures for various applications. In this article, we wil
3 min read
Python - Maximum frequency in Tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to find the maximum frequency element in the tuple. Tuple, being quite a popular container, this type of problem is common across the web development domain. Let's discuss certain ways in which this task can be perfo
5 min read
Python | Adding N to Kth tuple element
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let's discuss certain ways in which N can be added to Kth element of tuple in list. Method #1 : Using loop Using loops this task c
3 min read
Python - Keys Values equal frequency
Given a dictionary, count instances where keys are equal to values. Input : test_dict = {5:5, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 2 Explanation : At 2 instances, keys are equal to values.Input : test_dict = {5:4, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 1 Explanation : At 1 instance, key is equal to valu
4 min read
Python - Elements frequency in Tuple Matrix
Sometimes, while working with Python Tuple Matrix, we can have a problem in which we need to get the frequency of each element in it. This kind of problem can occur in domains such as day-day programming and web development domains. Let's discuss certain ways in which this problem can be solved. Inp
5 min read
Print a List of Tuples in Python
The task of printing a list of tuples in Python involves displaying the elements of a list where each item is a tuple. A tuple is an ordered collection of elements enclosed in parentheses ( ), while a list is an ordered collection enclosed in square brackets [ ]. Using print()print() function is the
2 min read
Python - Dictionary List Values Frequency
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the task of computing frequency of all the values in dictionary values lists. This is quite common problem and can have use cases in many domains. Let's discuss certain ways in which this task can be
6 min read