Python | Matrix True Summation
Last Updated :
14 Apr, 2023
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization like in data Science. Let’s discuss certain ways in which we can count True values in Matrix.
Method #1 : Using sum() + generator expression
This method uses the trick of adding 1 to the sum whenever the generator expression returns true. By the time list gets exhausted, summation of count of numbers matching a condition is returned.
Step-by-step approach :
- Import the chain function from the itertools module. chain function is used to concatenate two or more iterable objects.
- Define a list called test_list that contains multiple nested lists, each with two elements. The first element is an integer, and the second element is a boolean value.
- Print the original list using the print() function and str() conversion to display the original list in a string format.
- Use the chain.from_iterable() function to create a single iterator that contains all the elements from all the nested lists in test_list. from_iterable() function is used to create an iterator from nested lists.
- Use a generator expression to generate a sequence of True values that are present in the single iterator obtained from step 4.
- Use the sum() function to sum up all the True values generated in step 5.
- Store the result obtained in step 6 in a variable called res.
- Print the number of True elements present in the given matrix by converting res to a string using the str() function and concatenating it with a string message using the + operator.
- The program ends.
Python3
from itertools import chain
test_list = [[ 3 , True ], [ True , 6 ], [ True , 9 ]]
print ( "The original list is : " + str (test_list))
res = sum ( 1 for i in chain.from_iterable(test_list) if i = = True )
print ( "The number of True elements: " + str (res))
|
Output
The original list is : [[3, True], [True, 6], [True, 9]]
The number of True elements: 3
Time Complexity: O(n), where n is the length of list.
Auxiliary Space: O(1)
Method #2 : Using sum() + map()
map() does the task almost similar to the generator expression, difference is just the internal data structure employed by it is different hence more efficient.
Step by step approach :
- We start by importing the itertools module which provides a chain() function to concatenate multiple iterables into one iterable.
- We then initialize a 2D list (list of lists) called test_list with some values. Each sublist represents a row in a matrix.
- We print the original list using the print() function and concatenation operator + to join the string and list.
- We use the map() function to create a new iterable that contains 1s for every occurrence of True in test_list, and 0s otherwise. The lambda function lambda i: i == True returns True if the input argument is True and False otherwise.
- We use chain.from_iterable() function to convert the 2D list into a 1D list (i.e., chain all sublists into one list). This is because the map() function works on a single iterable, not a nested iterable.
- We pass the mapped iterable to the sum() function which adds up all the values in the iterable and returns the sum.
- Finally, we print the result using the print() function and concatenation operator + to join the string and integer.
Python3
from itertools import chain
test_list = [[ 3 , True ], [ True , 6 ], [ True , 9 ]]
print ( "The original list is : " + str (test_list))
res = sum ( map ( lambda i: i = = True , chain.from_iterable(test_list)))
print ( "The number of True elements: " + str (res))
|
Output
The original list is : [[3, True], [True, 6], [True, 9]]
The number of True elements: 3
Time complexity: O(n), where n is the total number of elements in the list “test_list”.
Auxiliary Space: O(1), as only a single integer value is stored in “res”.
Method #3 : Using extend()+count() methods
Step by step approach :
- Initialize a 2D list named test_list containing three inner lists.
- Print the original list using the print() function and concatenate the string “The original list is : ” with the list converted to a string using str().
- Create an empty list x to store all the elements of test_list.
- Iterate over each inner list i in test_list using a for loop.
- Extend the elements of i to the list x using the extend() method.
- Count the number of occurrences of True in the list x using the count() method and assign it to a variable named res.
- Print the result using the print() function and concatenate the string “The number of True elements: ” with the value of res converted to a string using str().
- End of program.
Python3
test_list = [[ 3 , True ], [ True , 6 ], [ True , 9 ]]
print ( "The original list is : " + str (test_list))
x = []
for i in test_list:
x.extend(i)
res = x.count( True )
print ( "The number of True elements: " + str (res))
|
Output
The original list is : [[3, True], [True, 6], [True, 9]]
The number of True elements: 3
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #4 : Using numpy module
Note: Install numpy module using command “pip install numpy”
Python3
import numpy as np
test_list = [[ 3 , True ], [ True , 6 ], [ True , 9 ]]
print ( "The original list is : " + str (test_list))
res = np. sum (np.array(test_list) = = True )
print ( "The number of True elements: " + str (res))
|
Output:
The original list is : [[3, True], [True, 6], [True, 9]]
The number of True elements: 3
Time Complexity: O(n), where n is the number of elements in the matrix.
Auxiliary Space: O(n), as the numpy array is stored in memory.
Method 5: using nested loops
The approach is to use nested loops to iterate over the elements of the matrix and count the number of True values.
Python3
test_list = [[ 3 , True ], [ True , 6 ], [ True , 9 ]]
print ( "The original list is : " + str (test_list))
count = 0
for row in test_list:
for element in row:
if element = = True :
count + = 1
print ( "The number of True elements: " + str (count))
|
Output
The original list is : [[3, True], [True, 6], [True, 9]]
The number of True elements: 3
Time Complexity: O(n), where n is the number of elements in the matrix.
Auxiliary Space: O(1)
Method #6 : Using opearor.countOf()
Approach
- Convert nested list to flatten list using extend() method
- Count the occurrence of True in flattened list using operator.countOf() method
- Display the count
Python3
test_list = [[ 3 , True ], [ True , 6 ], [ True , 9 ]]
print ( "The original list is : " + str (test_list))
import operator
x = []
for i in test_list:
x.extend(i)
res = operator.countOf(x, True )
print ( "The number of True elements: " + str (res))
|
Output
The original list is : [[3, True], [True, 6], [True, 9]]
The number of True elements: 3
Time Complexity : O(N)
Auxiliary Space : O(1)
Method #7: Using the built-in reduce() function to count the number of True values
Step-by-step approach:
- Import the reduce() function from functools module.
- Initialize the list of lists to be tested.
- Define a lambda function that performs two operations. First, it maps the elements in the sublist to 1 if the element is True or 0 if it is False. Then, it sums the resulting list. The accumulator variable stores the sum of all the True values encountered so far.
- Call the reduce() function and pass it the lambda function defined in step 3, the list of lists to be tested, and an initial value of 0.
- Print the result.
Python3
from functools import reduce
test_list = [[ 3 , True ], [ True , 6 ], [ True , 9 ]]
print ( "The original list is : " + str (test_list))
res = reduce ( lambda acc, sublist: acc + sum ( map ( lambda x: 1 if x = = True else 0 , sublist)), test_list, 0 )
print ( "The number of True elements: " + str (res))
|
Output
The original list is : [[3, True], [True, 6], [True, 9]]
The number of True elements: 3
Time complexity: O(nm) where n is the number of lists and m is the number of elements in each list.
Space complexity: O(1) as we are not using any extra space
Similar Reads
Python - Tuple Matrix Columns Summation
Sometimes, while working with Tuple Matrix, we can have a problem in which we need to perform summation of each column of tuple matrix, at the element level. This kind of problem can have application in Data Science domains. Let's discuss certain ways in which this task can be performed. Input : tes
8 min read
Python | Triple List Summation
There can be an application requirement to append elements of 2-3 lists to one list and perform summation. This kind of application has a potential to come into the domain of Machine Learning or sometimes in web development as well. Letâs discuss certain ways in which this particular task can be per
3 min read
Summation Matrix columns - Python
The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 min read
Python - Index Value Summation List
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies. Method 1: Nai
4 min read
Python | Column summation of tuples
Sometimes, we encounter a problem where we deal with a complex type of matrix column summation in which we are given a tuple and we need to perform the summation of its like elements. This has a good application in Machine Learning domain. Let's discuss certain ways in which this can be done. Method
7 min read
Python | Non-Repeating value Summation in Matrix
Sometimes we need to find the unique values in a list, which is comparatively easy and its summation has been discussed earlier. But we can also get a matrix as input i.e a list of lists, finding unique in them are discussed in this article. Letâs see certain ways in which this can be achieved. Meth
6 min read
Python - Summation of Unique elements
This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its summation. This operations has large no. of applications and hence itâs knowledge is good to have. Method 1 : Naive method + sum() In naive method, we simply t
5 min read
Python - Matrix Row subset
Sometimes, while working with Python Matrix, one can have a problem in which, one needs to extract all the rows that are a possible subset of any row of other Matrix. This kind of problem can have applications in data domains as a matrix is a key data type in those domains. Let's discuss certain way
7 min read
Python | Accumulative index summation in tuple list
Sometimes, while working with data, we can have a problem in which we need to find accumulative summation of each index in tuples. This problem can have applications in web development and competitive programming domain. Let's discuss certain way in which this problem can be solved. Method 1: Using
8 min read
Element indices Summation - Python
Our task is to calculate the sum of elements at specific indices in a list. This means selecting elements at specific positions and computing their sum. Given a list and a set of indices, the goal is to compute the sum of elements present at those indices. For example, given the list [10, 20, 30, 40
3 min read