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 code to demonstrate working of
# Elements frequency in Tuple
# Using defaultdict()
from collections import defaultdict
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
print("The original tuple is : " + str(test_tup))
res = defaultdict(int)
for ele in test_tup:
# incrementing frequency
res[ele] += 1
# printing result
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 code to demonstrate working of
# Elements frequency in Tuple
# Using Counter()
from collections import Counter
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# converting result back from defaultdict to dict
res = dict(Counter(test_tup))
# printing result
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 code to demonstrate working of
# Elements frequency in Tuple
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
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)
# printing result
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 code to demonstrate working of
# Elements frequency in Tuple
import operator as op
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
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)
# printing result
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.
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:
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.
from collections import Counter
from functools import reduce
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Elements frequency in Tuple
# Using reduce() + Counter()
res = reduce(lambda x, y: Counter(x) + Counter(y), [test_tup], Counter())
# printing result
print("Tuple elements frequency is : " + str(res))
#This code is contrinuted by Pushpa.
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.
import numpy as np
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# convert tuple to numpy array
arr = np.array(test_tup)
# calculate frequency of each element
unique, counts = np.unique(arr, return_counts=True)
freq_dict = dict(zip(unique, counts))
# print result
print("Tuple elements frequency is : " + str(freq_dict))
#This code is contributed by Vinay Pinjala
Output:
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
Time complexity: O(n log n).
Auxiliary Space: O(n)\