Tuesday, November 19, 2024
Google search engine
HomeLanguagesPython | Search in Nth Column of Matrix

Python | Search in Nth Column of Matrix

Sometimes, while working with Python Matrix, we can have a problem in which we need to check if an element is present or not. This problem is simpler, but a variation to it can be to perform a check in a particular column of Matrix. Let’s discuss a shorthand by which this task can be performed. 

Method 1: Using any() + list comprehension

This task can be performed using a combination of the above functions in which we imply list comprehension for iteration and support tasks and any() can be used to check for any occurrence of the desired character. 

Step-by-step approach ;

  1. Initialize a list of lists test_list containing three sub-lists, each containing three integer values.
  2. Print the original list test_list using the print() function along with a string message.
  3. Initialize a variable N with the value 1, indicating the index of the column in which we want to search for the element.
  4. Initialize a variable ele with the value 3, indicating the element we want to search for in the specified column.
  5. Use the any() function along with a list comprehension to check if the element ele exists in the Nth column of the matrix test_list. The list comprehension iterates through each sublist of test_list and checks if the element at index N of the sublist is equal to ele. The any() function returns True if any element in the list comprehension is True, indicating that the element ele exists in the specified column.
  6. Store the result of the search in the variable res.
  7. Print the result of the search using the print() function along with a string message.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Search in Nth Column of Matrix
# Using any() + list comprehension
 
# initializing list
test_list = [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing N
N = 1
 
# initializing num
ele = 3
 
# Search in Nth Column of Matrix
# Using any() + list comprehension
res = any(sub[N] == ele for sub in test_list)
 
# Printing result
print("Does element exists in particular column : " + str(res))


Output

The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True

Time complexity: O(n), where n is the total number of elements in the matrix because we have to iterate through all the elements of the matrix to check if the element exists in the particular column.

Auxiliary space: O(1), because only a few variables are used and the memory usage does not depend on the size of the input.

Method 2: Using map() and lambda function:

Using the map() function along with a lambda function allows you to apply a specific operation to each element in an iterable such as a list or matrix. In this case, you can use the lambda function to check the Nth element of each row and return a list of boolean values indicating whether the element was present in that row or not. The map() function will apply the lambda function to each element in the matrix (rows), so the time complexity of this approach would be O(n) where n is the number of rows in the matrix. And Auxiliary space of this approach would be O(n) as well, as it creates a new list of booleans for each element in the matrix.

Here is an example of how to use the map() function along with a lambda function to check if an element is present in a particular column of a matrix:

Python3




# initializing list
test_list = [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing N
N = 1
 
# initializing num
ele = 3
 
# Using map() and lambda function to check if an element is present in a particular column of a matrix
res = True in list(map(lambda x: x[N] == ele, test_list))
 
# Printing result
print("Does element exists in particular column : " + str(res))
 
# This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True

Time complexity: O(n), where n is the number of rows in the matrix (list of lists). 
Auxiliary space: O(1), as it only uses a few constant-size variables (N, ele, res) and does not create any additional data structures.

Method 3: Using a for loop to iterate over each row and then accessing the element at the Nth column, comparing it with the desired element and setting a flag if found.

This program searches for a specific element in a particular column of a matrix represented as a list of lists. It initializes the matrix, the column to search (N), and the element to find (ele). It then uses a for loop to iterate through each row of the matrix and checks if the element exists in the Nth column of that row. If the element is found in the specified column, it sets the variable “found” to True and breaks out of the loop. Finally, it prints whether the element exists in the particular column or not.

Python3




# Python3 code to demonstrate working of
# Search in Nth Column of Matrix
# Using a for loop
 
# initializing list
test_list = [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing N
N = 1
 
# initializing num
ele = 3
 
# Search in Nth Column of Matrix
# Using a for loop
found = False
for row in test_list:
    if row[N] == ele:
        found = True
        break
 
# Printing result
print("Does element exists in particular column : " + str(found))


Output

The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True

The time complexity of this method is O(n), where n is the number of rows in the matrix
The space complexity of this method is O(1), as we only use a constant amount of extra space to store the variables N, ele, and found.

Method 4: numpy library

 step-by-step approach:

  1. Import the numpy library
  2. Initialize the list as a numpy array
  3. Initialize the Nth column index and the desired element
  4. Use numpy.any() function to check if the desired element exists in the Nth column
  5. Print the result

Python3




# import numpy library
import numpy as np
 
# initializing list as numpy array
test_list = np.array([[1, 4, 5], [6, 7, 8], [8, 3, 0]])
 
# printing list
print("The original list : ")
print(test_list)
 
# initializing N
N = 1
 
# initializing num
ele = 3
 
# Search in Nth Column of Matrix
# Using numpy.any()
found = np.any(test_list[:, N] == ele)
 
# Printing result
print("Does element exists in particular column : " + str(found))


Output: 

The original list : 
[[1 4 5]
[6 7 8]
[8 3 0]]
Does element exists in particular column : True

Time complexity: O(n), where n is the number of elements in the matrix.
Auxiliary space: O(1)

Method 5: Using pandas library.

Step-by-step approach:

  1. Import pandas library.
  2. Create a DataFrame using the numpy array.
  3. Use the ‘iloc’ function to extract the Nth column.
  4. Use the ‘any’ function to check if the element exists in the extracted column.
  5. Print the result.

Python3




# Import NumPy and pandas library
import numpy as np
import pandas as pd
 
# Initializing list as numpy array
test_list = np.array([[1, 4, 5], [6, 7, 8], [8, 3, 0]])
 
# Create a DataFrame
df = pd.DataFrame(test_list)
 
# Initializing N
N = 1
 
# Initializing num
ele = 3
 
# Search in Nth Column of Matrix Using pandas
found = df.iloc[:, N].isin([ele]).any()
 
# Printing result
print("Does element exists in particular column : " + str(found))


Output:

Does element exists in particular column : True

Time complexity: O(m*n), where m is the number of rows and n is the number of columns in the matrix.
Auxiliary space: O(m*n), as we create a DataFrame to store the matrix.

Method 6: Using the in-built function index()

Step-by-step approach:

  1. Initialize a 2D list of integers called test_list with three sublists of three integers each.
  2. Print the original list using print() and str().
  3. Initialize an integer variable N to 1. This variable represents the column we want to check for the presence of ele.
  4. Initialize an integer variable ele to 3. This is the element we want to check for in the column.
  5. Set a boolean variable res to False. This variable will store the result of whether the element exists in the column.
  6. Use a for loop to iterate through each sublist in test_list.
  7. Within the loop, use a try-except block to catch a ValueError if ele is not found in the current sublist.
  8. If ele is found in the current sublist, use the index() function to get the index of ele in the sublist.
  9. If the index of ele in the sublist equals N, set res to True and break out of the loop.
  10. If ele is not found in the current sublist, continue to the next sublist in the loop.
  11. After the loop finishes, print the result using print() and str().

Below is the implementation of the above approach:

Python3




# initializing list
test_list = [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing N
N = 1
 
# initializing num
ele = 3
 
# Using the in-built function index() to check if an element is present in a particular column of a matrix
res = False
for lst in test_list:
    try:
        idx = lst.index(ele)
        if idx == N:
            res = True
            break
    except ValueError:
        pass
 
# Printing result
print("Does element exists in particular column : " + str(res))
 
# This code is contributed by ChatGPT.


Output

The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True

Time complexity: O(n*m) where n is the number of rows and m is the number of columns in test_list.
Auxiliary space: O(1) because it uses a constant amount of memory regardless of the size of test_list

Method 7: Using itertools:

  1. Import the itertools module
  2. Initialize the original list
  3. Initialize the column index (N) and the element to search (ele)
  4. Use itertools.chain() to flatten the nested list into a single list
  5. Use any() to check if the element exists in the Nth position of the flattened list
  6. Return the boolean result

Python3




import itertools
 
# initializing list
test_list = [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing N
N = 1
 
# initializing num
ele = 3
 
# Using itertools.chain() to flatten the nested list
flat_list = list(itertools.chain(*test_list))
 
# Using any() to check if the element exists in the Nth position of the flattened list
res = any(flat_list[i] == ele for i in range(N, len(flat_list), len(test_list)))
 
# Printing result
print("Does element exists in particular column : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True

Time complexity: O(n^2) where n is the number of elements in the matrix. This is because itertools.chain() requires iterating over the entire matrix and then flattening it, and any() also requires iterating over the entire flattened list.

Space complexity: O(n) for the flattened list, since it requires creating a new list that contains all the elements of the matrix.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments