Open In App

Python | Matrix True Summation

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

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 :

  1. Import the chain function from the itertools module. chain function is used to concatenate two or more iterable objects.
  2. 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.
  3. Print the original list using the print() function and str() conversion to display the original list in a string format.
  4. 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.
  5. Use a generator expression to generate a sequence of True values that are present in the single iterator obtained from step 4.
  6. Use the sum() function to sum up all the True values generated in step 5.
  7. Store the result obtained in step 6 in a variable called res.
  8. 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.
  9. The program ends.

Python3




# Python 3 code to demonstrate
# Matrix True Summation
# using sum() + generator expression
from itertools import chain
 
# initializing list
test_list = [[3, True], [True, 6], [True, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using sum() + generator expression
# Matrix True Summation
res = sum(1 for i in chain.from_iterable(test_list) if i == True)
 
# printing result
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 : 

  1. We start by importing the itertools module which provides a chain() function to concatenate multiple iterables into one iterable.
  2. We then initialize a 2D list (list of lists) called test_list with some values. Each sublist represents a row in a matrix.
  3. We print the original list using the print() function and concatenation operator + to join the string and list.
  4. 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.
  5. 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.
  6. We pass the mapped iterable to the sum() function which adds up all the values in the iterable and returns the sum.
  7. Finally, we print the result using the print() function and concatenation operator + to join the string and integer.

Python3




# Python 3 code to demonstrate
# Matrix True Summation
# using sum()+ map()
from itertools import chain
 
# initializing list
test_list = [[3, True], [True, 6], [True, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using sum()+ map()
# Matrix True Summation
res = sum(map(lambda i: i == True, chain.from_iterable(test_list)))
 
# printing result
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 :

  1. Initialize a 2D list named test_list containing three inner lists.
  2. 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().
  3. Create an empty list x to store all the elements of test_list.
  4. Iterate over each inner list i in test_list using a for loop.
  5. Extend the elements of i to the list x using the extend() method.
  6. Count the number of occurrences of True in the list x using the count() method and assign it to a variable named res.
  7. 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().
  8. End of program.

Python3




# Python 3 code to demonstrate
# Matrix True Summation
 
# initializing list
test_list = [[3, True], [True, 6], [True, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
 
# Matrix True Summation
x=[]
for i in test_list:
    x.extend(i)
res=x.count(True)
 
# printing result
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




#Python 3 code to demonstrate
#Matrix True Summation
#using numpy module
import numpy as np
 
#initializing list
test_list = [[3, True], [True, 6], [True, 9]]
 
#printing original list
print("The original list is : " + str(test_list))
 
#using numpy module
#Matrix True Summation
res = np.sum(np.array(test_list) == True)
 
#printing result
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




# initializing list
test_list = [[3, True], [True, 6], [True, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using nested loops
# Matrix True Summation
count = 0
for row in test_list:
    for element in row:
        if element == True:
            count += 1
 
# printing result
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

  1. Convert nested list to flatten list using extend() method
  2. Count the occurrence of True in flattened list using operator.countOf() method
  3. Display the count

Python3




# Python 3 code to demonstrate
# Matrix True Summation
 
# initializing list
test_list = [[3, True], [True, 6], [True, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
 
# Matrix True Summation
import operator
x=[]
for i in test_list:
    x.extend(i)
res=operator.countOf(x,True)
 
# printing result
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:

  1. Import the reduce() function from functools module.
  2. Initialize the list of lists to be tested.
  3. 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.
  4. 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.
  5. Print the result.

Python3




# Python 3 code to demonstrate
# Matrix True Summation
# using reduce()
 
from functools import reduce
 
# initializing list
test_list = [[3, True], [True, 6], [True, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using reduce()
# Matrix True Summation
res = reduce(lambda acc, sublist: acc + sum(map(lambda x: 1 if x == True else 0, sublist)), test_list, 0)
 
# printing result
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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads