![]() |
VOOZH | about |
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.
Input : test_list = [[(4, 5), (3, 2)], [(2, 2)]]
Output : {4: 1, 5: 1, 3: 1, 2: 3}Input : test_list = [[(4, 5), (3, 2)]]
Output : {4: 1, 5: 1, 3: 1, 2: 1}
Method #1 : Using nested chain() + "*" operator + Counter()
The combination of the above functions can be used to solve this problem. In this, we perform the task of getting frequency using Counter() and nested chain to cater the nestings, and the "*" operator is used to perform unpacking and packing of each element.
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements
Method #2: Using chain.from_iterables() + Counter()
The combination of the above functions can be used to solve this problem. In this, we perform the task of packing, unpacking, and flattening using chain.from_iterables().
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}Time Complexity: O(n^2), where n is the total number of tuples in the input "test_list".
Auxiliary Space: O(n)
Method #3 : Using extend() and count() methods
Approach
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
Elements frequency : {1: 1, 2: 4, 3: 1, 4: 1, 5: 3}Time Complexity : O(N*N)
Auxiliary Space : O(N)
Method #4 : Using extend() and operator.countOf() methods
Approach
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
Elements frequency : {1: 1, 2: 4, 3: 1, 4: 1, 5: 3}Time Complexity : O(N*N) N -length of extended list(x)
Auxiliary Space : O(N) N - length of dictionary
Method #5: Using defaultdict()
Step-by-step approach:
Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}Time Complexity: O(n^2), where n is the length of the largest nested tuple in the test_list.
Auxiliary Space: O(m), where m is the number of unique elements in the test_list.