Python - Matrix elements Frequencies Counter
Last Updated :
26 Mar, 2023
Sometimes, while working with python Matrix, we can have a problem in which we need to find frequencies of all elements in Matrix. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using Counter() + sum() + map() The combination of above methods can be used to perform this task. In this, we perform task of counting elements using Counter() and extending the logic to each row is performed using sum() and map().
Python3
# Python3 code to demonstrate
# Matrix elements Frequencies Counter
# using Counter() + sum() + map()
from collections import Counter
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Matrix elements Frequencies Counter
# using Counter() + sum() + map()
res = dict(sum(map(Counter, test_list), Counter()))
# printing result
print ("The frequencies dictionary is : " + str(res))
Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The frequencies dictionary is : {2: 1, 4: 2, 5: 3, 6: 2, 7: 1}
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
Method #2 : Using chain() + Counter() The combination of above functions can be used to perform this task. In this, we flatten the matrix using chain() and compute frequency using Counter().
Python3
# Python3 code to demonstrate
# Matrix elements Frequencies Counter
# using Counter() + chain()
from collections import Counter
import itertools
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# Matrix elements Frequencies Counter
# using Counter() + chain()
res = dict(Counter(itertools.chain(*test_list)))
# printing result
print ("The frequencies dictionary is : " + str(res))
Output : The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The frequencies dictionary is : {2: 1, 4: 2, 5: 3, 6: 2, 7: 1}
Method #3 : Using extend(),set() and count() methods
Python3
# Python3 code to demonstrate
# Matrix elements Frequencies Counter
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
res=dict()
a=[]
for i in test_list:
a.extend(i)
b=set(a)
for i in b:
res[i]=a.count(i)
# printing result
print ("The frequencies dictionary is : " + str(res))
OutputThe original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The frequencies dictionary is : {2: 1, 4: 2, 5: 3, 6: 2, 7: 1}
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method #4 : Using extend(),set() and operator.countOf() methods
Python3
# Python3 code to demonstrate
# Matrix elements Frequencies Counter
import operator as op
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
res=dict()
a=[]
for i in test_list:
a.extend(i)
b=set(a)
for i in b:
res[i]=op.countOf(a,i)
# printing result
print ("The frequencies dictionary is : " + str(res))
OutputThe original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The frequencies dictionary is : {2: 1, 4: 2, 5: 3, 6: 2, 7: 1}
Time Complexity: O(N*N)
Auxiliary Space: O(N*N)
Method #5 :Using itertools.chain() and collections.Counter():
Algorithm :
- Import the itertools and collections modules.
- Initialize a list test_list with the input matrix.
- Flatten the input matrix using itertools.chain.from_iterable().
- Count the frequencies of each element in the flattened list using collections.Counter().
- Store the result in a dictionary res.
- Print the result.
Python3
import itertools
import collections
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print("The original list is : " + str(test_list))
# flatten the list using chain()
flat_list = list(itertools.chain.from_iterable(test_list))
# count the frequencies using Counter()
res = collections.Counter(flat_list)
print("The frequencies dictionary is : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The frequencies dictionary is : Counter({5: 3, 4: 2, 6: 2, 2: 1, 7: 1})
Time complexity: The time complexity of this algorithm is O(n), where n is the total number of elements in the input matrix. The itertools.chain.from_iterable() function and the collections.Counter() function both have linear time complexity with respect to the number of elements in the input list.
Space complexity: The space complexity of this algorithm is O(n), where n is the total number of elements in the input matrix. This is because the flattened list and the dictionary both require memory proportional to the number of elements in the input matrix. Note that the space complexity could be reduced by using an in-place counting algorithm instead of creating a dictionary, but this would require more complex code.
Similar Reads
Python - Elements frequency count in multiple lists
Sometimes while working with Python lists we can have a problem in which we need to extract the frequency of elements in list. But this can be added work if we have more than 1 list we work on. Let's discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension
6 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
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 | 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
Sort List Elements by Frequency - Python
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 - Similar Consecutive elements frequency
Sometimes, while working with Python, we can have a problem in which we have to find the occurrences of elements that are present consecutively. This problem have usage in school programming and data engineering. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop
5 min read
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 | Count of Matching i, j index elements
Sometimes, while programming, we can have a problem in which we need to check for ith and jth character of each string. We may require to extract count of all strings with similar ith and jth characters. Letâs discuss certain ways in which this task can be performed. Method #1 : Using loop This is b
4 min read
Frequency of Elements from Other List - Python
We are given a list of elements and another list containing specific values and our task is to count the occurrences of these specific values in the first list "a" and return their frequencies. For example: a = [1, 2, 2, 3, 4, 2, 5, 3, 1], b = [1, 2, 3]. Here b contains the elements whose frequency
3 min read
Python | Group list elements based on frequency
Given a list of elements, write a Python program to group list elements and their respective frequency within a tuple. Examples: Input : [1, 3, 4, 4, 1, 5, 3, 1] Output : [(1, 3), (3, 2), (4, 2), (5, 1)] Input : ['x', 'a', 'x', 'y', 'a', 'x'] Output : [('x', 3), ('a', 2), ('y', 1)] Method #1: List c
5 min read