Open In App

Python – Count the frequency of matrix row length

Last Updated : 22 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Matrix, the task is to write a Python program to get the count frequency of its rows lengths.

Input : test_list = [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]]

Output : {3: 2, 2: 2, 1: 1}

Explanation : 2 lists of length 3 are present, 2 lists of size 2 and 1 of 1 length is present.

Input : test_list = [[6, 3, 1], [8, 9], [10, 12, 7], [4, 11]]

Output : {3: 2, 2: 2}

Explanation : 2 lists of length 3 are present, 2 lists of size 2.

Method #1 : Using dictionary + loop

In this we check for each row length, if length has occurred in the memorize dictionary, then the result is incremented or if a new size occurs, the element is registered as new.

Python3




# Python3 code to demonstrate working of
# Row lengths counts
# Using dictionary + loop
 
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
             [10, 12, 7], [4, 11]]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = dict()
for sub in test_list:
 
    # initializing incase of new length
    if len(sub) not in res:
        res[len(sub)] = 1
 
    # increment in case of length present
    else:
        res[len(sub)] += 1
 
# printing result
print("Row length frequencies : " + str(res))


Output

The original list is : [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]]
Row length frequencies : {3: 2, 2: 2, 1: 1}

Time complexity: O(n), where n is the total number of sublists in the input list.
Auxiliary space complexity: O(n), where n is the total number of sublists in the input list. The dictionary used to store the frequency of each length takes up O(n) space.

Method #2 : Using Counter() + map() + len()

In this, map() and len() get the lengths of each sublist in the matrix, Counter is used to keep the frequency of each of the lengths.

Python3




# Python3 code to demonstrate working of
# Row lengths counts
# Using Counter() + map() + len()
from collections import Counter
 
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
             [10, 12, 7], [4, 11]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Counter gets the frequencies of counts
# map and len gets lengths of sublist
res = dict(Counter(map(len, test_list)))
 
# printing result
print("Row length frequencies : " + str(res))


Output:

The original list is : [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]]
Row length frequencies : {3: 2, 2: 2, 1: 1}

Time complexity: O(n), where n is the total number of elements in the input list.
Auxiliary space: O(k), where k is the number of unique row lengths in the input list.

Method #3 : Using count() method

Python3




# Python3 code to demonstrate working of
# Row lengths counts
# Using dictionary + loop
 
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
             [10, 12, 7], [4, 11]]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = dict()
x = []
for sub in test_list:
    x.append(len(sub))
y = set(x)
for i in y:
    res[i] = x.count(i)
 
# printing result
print("Row length frequencies : " + str(res))


Output

The original list is : [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]]
Row length frequencies : {1: 1, 2: 2, 3: 2}

Time complexity: O(n^2) where n is the length of the input list. 
Auxiliary space: O(n) where n is the length of the input list. 

Method #4 : Using operator.countOf() method

Python3




# Python3 code to demonstrate working of
# Row lengths counts
# Using dictionary + loop
import operator as op
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
             [10, 12, 7], [4, 11]]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = dict()
x = []
for sub in test_list:
    x.append(len(sub))
y = set(x)
for i in y:
    res[i] = op.countOf(x,i)
 
# printing result
print("Row length frequencies : " + str(res))


Output

The original list is : [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]]
Row length frequencies : {1: 1, 2: 2, 3: 2}

Time Complexity: O(N*N)
Auxiliary Space:  O(N*N)

Method #6: Using list comprehension and dictionary

  1. Initialize a list of sublists test_list.
  2. Print the original list using the print() function.
  3. Use a list comprehension to create a new list lengths containing the lengths of all sublists in test_list. The len() function is used to get the length of each sublist.
  4. Use a dictionary comprehension to count the frequency of each length in the lengths list obtained in step 3. The key of each key-value pair in the resulting dictionary is a length, and the value is the number of times that length appears in the lengths list. The count() method is used to count the frequency of each length.
  5. Store the resulting dictionary in the variable res.
  6. Print the resulting dictionary using the print() function.

Python3




# Python3 code to demonstrate working of
# Row lengths counts
# Using list comprehension and dictionary
 
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
             [10, 12, 7], [4, 11]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using list comprehension and dictionary
lengths = [len(sub) for sub in test_list]
res = {length: lengths.count(length) for length in lengths}
 
# printing result
print("Row length frequencies : " + str(res))


Output

The original list is : [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]]
Row length frequencies : {3: 2, 2: 2, 1: 1}

Time complexity: O(n), where n is the length of test_list.
Auxiliary space: O(k), where k is the number of distinct row lengths in test_list.



Previous Article
Next Article

Similar Reads

Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Sort Dataframe according to row frequency in Pandas
In this article, we will discuss how to use count() and sort_values() in pandas. So the count in pandas counts the frequency of elements in the dataframe column and then sort sorts the dataframe according to element frequency. count(): This method will show you the number of values for each column in your DataFrame.sort_values(): This method helps
2 min read
Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
Find the number of negative numbers in a column-wise / row-wise sorted matrix M[][]. Suppose M has n rows and m columns. Example: Input: M = [-3, -2, -1, 1] [-2, 2, 3, 4] [4, 5, 7, 8] Output : 4 We have 4 negative numbers in this matrix We strongly recommend you to minimize your browser and try this yourself first. Naive Solution: Here's a naive, n
15+ min read
Python - Incremental K sized Row Matrix Initialization
Sometimes, while working with Python, we can have a problem in which we need to perform initialization of matrix with Incremental numbers. This kind of application can come in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + list slicing This task can be performed in brute way using loop.
6 min read
Python | Remove False row from matrix
Sometimes, while handling data, especially in the Machine Learning domain, we need to go through a lot of incomplete or empty data. We sometimes need to eliminate the rows which do not contain a value in any of the columns. Let's discuss certain ways to remove the rows that have all False values as list columns. Method #1 : Using list comprehension
9 min read
Python | Row lengths in Matrix
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the lengths of rows of matrix in uneven sized matrix. Let's discuss certain ways in which this problem can be solved. Method #1 : Using max() + map() + sum() + list comprehension The combination
4 min read
Python | sympy.Matrix.row() method
With the help of sympy.Matrix.row() method, we can extract the rows of the matrix. Syntax : sympy.Matrix.row() Return : Return the row of a matrix. Example #1 : In the given example we can see that the sympy.Matrix().row() method is used to extract the rows of a matrix. # Import all the methods from sympy from sympy import * # use the row() method
1 min read
Python - Consecutive Row summation in Matrix
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the sum between the like indices when compared with the next list. The sum between the like elements in that index is returned. Let’s discuss certain ways in which this task can be performed. Method #1 : Using sum()
5 min read
Python | Remove last element from each row in Matrix
Sometimes, while working with Matrix data, we can have a stray element attached at rear end of each row of matrix. This can be undesired at times and wished to be removed. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + del + list slicing The combination of the above functionalities can be used to perform thi
6 min read
Python - Row with Minimum Sum in Matrix
We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development. Method #1 : Using reduce() + lambda The above two function can help us achieving this part
4 min read
three90RightbarBannerImg