Python – Elements frequency in Tuple
Last Updated :
18 May, 2023
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 defaultdict()
In this, we perform task of getting all elements and assigning frequency using defaultdict which maps each element with key and then frequency can be incremented.
Python3
from collections import defaultdict
test_tup = ( 4 , 5 , 4 , 5 , 6 , 6 , 5 , 5 , 4 )
print ( "The original tuple is : " + str (test_tup))
res = defaultdict( int )
for ele in test_tup:
res[ele] + = 1
print ( "Tuple elements frequency is : " + str ( dict (res)))
|
Output
The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
Time complexity: O(n), where n is the length of the tuple test_tup. This is because the program iterates through the tuple once to increment the frequency of each element using a dictionary. The += operation and dictionary lookup both take constant time.
Auxiliary space: O(n), where n is the length of the tuple test_tup. This is because the program uses a dictionary to store the frequency of each element in the tuple, which can potentially have n unique elements.
Method #2 : Using Counter()
This is straight forward way to solve this problem. In this, we just employ this function and it returns frequency of elements in container, in this case tuple.
Python3
from collections import Counter
test_tup = ( 4 , 5 , 4 , 5 , 6 , 6 , 5 , 5 , 4 )
print ( "The original tuple is : " + str (test_tup))
res = dict (Counter(test_tup))
print ( "Tuple elements frequency is : " + str (res))
|
Output
The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
Time complexity: O(n), where n is the number of elements in the tuple.
Auxiliary space: O(n), as the Counter() method creates a dictionary that stores the frequency of each element in the tuple.
Method #3 : Using count() method.
Python3
test_tup = ( 4 , 5 , 4 , 5 , 6 , 6 , 5 , 5 , 4 )
print ( "The original tuple is : " + str (test_tup))
res = dict ()
x = list (test_tup)
y = []
for i in x:
if i not in y:
y.append(i)
for i in y:
res[i] = x.count(i)
print ( "Tuple elements frequency is : " + str (res))
|
Output
The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
The time complexity of this program is O(n^2) because of the nested loops used to count the frequency of each element.
The auxiliary space complexity of this program is O(n) because the program uses two lists x and y to store the tuple elements and unique elements, respectively, and a dictionary res to store the frequency count of each element.
Method #4 : Using operator.countOf() method.
Python3
import operator as op
test_tup = ( 4 , 5 , 4 , 5 , 6 , 6 , 5 , 5 , 4 )
print ( "The original tuple is : " + str (test_tup))
res = dict ()
x = list (test_tup)
y = []
for i in x:
if i not in y:
y.append(i)
for i in y:
res[i] = op.countOf(x,i)
print ( "Tuple elements frequency is : " + str (res))
|
Output
The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
Time Complexity: O(N), where n is the length of the given tuple
Auxiliary Space: O(n)
Method 5:dictionary and loop over the elements in the tuple to count their frequency.
This code is designed to count the frequency of each element in the tuple test_tup. It does this by creating an empty dictionary freq_dict to store the counts, and then looping over each element of the tuple. For each element, it checks if that element is already a key in the dictionary freq_dict. If it is, it increments the value associated with that key (which represents the count of that element in the tuple). If it isn’t, it adds a new key to the dictionary with a value of 1. Once the loop has finished, the code prints out the resulting dictionary, which contains the counts for each unique element in the tuple.
Python3
test_tup = ( 4 , 5 , 4 , 5 , 6 , 6 , 5 , 5 , 4 )
freq_dict = {}
for elem in test_tup:
if elem in freq_dict:
freq_dict[elem] + = 1
else :
freq_dict[elem] = 1
print ( "Tuple elements frequency is : " + str (freq_dict))
|
Output
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
Time complexity: O(n), where n is the length of the tuple.
Auxiliary space: O(k), where k is the number of unique elements in the tuple.
Method 6: using the built-in function set()
Using the built-in function set() to create a set of unique elements in the tuple and then using a list comprehension to count the frequency of each unique element:
Python3
test_tup = ( 4 , 5 , 4 , 5 , 6 , 6 , 5 , 5 , 4 )
unique_elems = set (test_tup)
freq_dict = {elem: [x for x in test_tup].count(elem) for elem in unique_elems}
print ( "Tuple elements frequency is : " + str (freq_dict))
|
Output
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
Time complexity: O(n^2) due to the nested loop in the list comprehension,
Auxiliary space: O(n) to store the dictionary.
Method 7: Using reduce():
Algorithm:
- Import the required modules.
- Initialize a tuple with elements.
- Apply reduce() function on the tuple with Counter() function and Counter() function as the initial value.
- Print the result.
Python3
from collections import Counter
from functools import reduce
test_tup = ( 4 , 5 , 4 , 5 , 6 , 6 , 5 , 5 , 4 )
print ( "The original tuple is : " + str (test_tup))
res = reduce ( lambda x, y: Counter(x) + Counter(y), [test_tup], Counter())
print ( "Tuple elements frequency is : " + str (res))
|
Output
The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : Counter({5: 4, 4: 3, 6: 2})
Time Complexity:
The time complexity of this code is O(nlogn) because sorting is required for tuples and dictionaries, and dictionaries are used by the Counter() function.
Auxiliary Space:
The space complexity of this code is O(n) because additional space is used to store the output.
Method 8: Using numpy:
- Import the numpy module.
- Initialize a tuple test_tup with some values.
- Convert the tuple to a numpy array using np.array().
- Use np.unique() function to get the unique elements in the numpy array and their corresponding counts using the return_counts=True parameter.
- Use the zip() function to combine the two arrays into a dictionary, which is stored in the freq_dict variable.
Print the dictionary freq_dict.
Python3
import numpy as np
test_tup = ( 4 , 5 , 4 , 5 , 6 , 6 , 5 , 5 , 4 )
arr = np.array(test_tup)
unique, counts = np.unique(arr, return_counts = True )
freq_dict = dict ( zip (unique, counts))
print ( "Tuple elements frequency is : " + str (freq_dict))
|
Output:
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
Time complexity: O(n log n).
Auxiliary Space: O(n)\
Similar Reads
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
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 - Elements Frequency in Mixed Nested Tuple
Sometimes, while working with Python data, we can have a problem in which we have data in the form of nested and non-nested forms inside a single tuple, and we wish to count the element frequency in them. This kind of problem can come in domains such as web development and Data Science. Let's discus
8 min read
Python - Step Frequency of elements in List
Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
4 min read
Python - Similar index elements frequency
Sometimes, while working with Python list, we can have a problem in which we need to check if one element has similar index occurrence in other list. This can have possible application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using sum() + zip() The
7 min read
Python - List Frequency of Elements
We are given a list we need to count frequencies of all elements in given list. For example, n = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] we need to count frequencies so that output should be {4: 4, 3: 3, 2: 2, 1: 1}. Using collections.Countercollections.Counter class provides a dictionary-like structure that
2 min read
Python | Sort list elements by frequency
Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
3 min read
Python - Restrict Elements Frequency in List
Given a List, and elements frequency list, restrict frequency of elements in list from frequency list. Input : test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6], restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 1} Output : [1, 4, 5, 4, 4, 6] Explanation : Limit of 1 is 1, any occurrence more than that is removed.
5 min read
Python | N element incremental tuples
Sometimes, while working with data, we can have a problem in which we require to gather a data that is of the form of sequence of increasing element tuple with each tuple containing the element N times. Let's discuss certain ways in which this task can be performed. Method #1 : Using generator expre
5 min read
Python | Elements with Frequency equal K
This is one of the most essential operation that programmer quite often comes in terms with. Be it development or competitive programming, this utility is quite essential to master as it helps to perform many tasks that involve this task to be its subtask. Lets discuss approach to achieve this opera
3 min read