Python - Check Similar elements in Matrix rows
Last Updated :
04 Apr, 2023
Given a Matrix and list, the task is to write a Python program to check if all the matrix elements of the row are similar to the ith index of the List.
Input : test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Output : True
Explanation : All rows have same elements.
Input : test_list = [[1, 1, 4], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Output : False
Explanation : All rows don't have same elements.
Method #1: Using loop
In this, we iterate through each row and check for its similar number in the list, if all the elements in a row are the same as an ith element in the List, true is returned, else false.
step-by-step approach :
- Initialize a matrix with some values using a nested list. The matrix is assigned to the variable test_list.
- Print the original matrix using the print() function.
- Initialize a list with some target values. The list is assigned to the variable tar_list.
- Initialize a boolean variable res to True which is used to store the result of the comparison.
- Initialize an integer variable flag to 0 which is used to break out of the outer loop if a mismatch is found.
- Loop through each index in the range of the length of the test_list. The variable idx is used to hold the current index value.
- Within the outer loop, loop through each element in the current row of test_list[idx]. The variable ele is used to hold the current element value.
- Check if the current element value is equal to the corresponding index element value in tar_list. If they are not equal, set res to False, set flag to 1, and break out of the inner loop.
- If flag is set to 1 (meaning a mismatch was found), break out of the outer loop as well.
- After the loops have completed, print the result of the comparison using the print() function.
Python3
# Python3 code to demonstrate working of
# Similar all elements as List in Matrix rows
# Using loop
# initializing Matrix
test_list = [[1, 1, 1], [4, 4],
[3, 3, 3], [5, 5, 5, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing tar_list
tar_list = [1, 4, 3, 5]
res = True
flag = 0
for idx in range(len(test_list)):
for ele in test_list[idx]:
# checking for row index
# equal to list index elements
if ele != tar_list[idx]:
res = False
flag = 1
break
if flag:
break
# printing result
print("Are row index element similar\
to list index element ? : " + str(res))
Output:
The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Are row index element similar to list index element ? : True
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Method #2 : Using all() + generator expression
In this, we check for all elements to be equal using all(), and check for all elements follow this pattern using all() again. The iteration of elements and rows is done using generator expression.
Example:
Python3
# Python3 code to demonstrate working of
# Similar all elements as List in Matrix rows
# Using all() + generator expression
# initializing Matrix
test_list = [[1, 1, 1], [4, 4],
[3, 3, 3], [5, 5, 5, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing tar_list
tar_list = [1, 4, 3, 5]
# nested all() used to check each element and rows
res = all(all(ele == tar_list[idx] for ele in test_list[idx])
for idx in range(len(test_list)))
# printing result
print("Are row index element\
similar to list index element ? : " + str(res))
Output:
The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Are row index element similar to list index element ? : True
Time Complexity: O(n*m)
Auxiliary Space: O(k)
Method #3 : Using count() and len() methods
Python3
# Python3 code to demonstrate working of
# Similar all elements as List in Matrix rows
# Using loop
# initializing Matrix
test_list = [[1, 1, 1], [4, 4],
[3, 3, 3], [5, 5, 5, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing tar_list
tar_list = [1, 4, 3, 5]
cnt = 0
res = False
for i in range(0, len(tar_list)):
if(test_list[i].count(tar_list[i]) == len(test_list[i])):
cnt += 1
if(cnt == len(test_list)):
res = True
# printing result
print("Are row index element similar to list index element ? : " + str(res))
OutputThe original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Are row index element similar to list index element ? : True
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), no space is required
Method #4 : Using operator.countOf() method
Python3
# Python3 code to demonstrate working of
# Similar all elements as List in Matrix rows
# Using loop
import operator as op
# initializing Matrix
test_list = [[1, 1, 1], [4, 4],
[3, 3, 3], [5, 5, 5, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing tar_list
tar_list = [1, 4, 3, 5]
cnt = 0
res = False
for i in range(0, len(tar_list)):
if(op.countOf(test_list[i], tar_list[i]) == len(test_list[i])):
cnt += 1
if(cnt == len(test_list)):
res = True
# printing result
print("Are row index element similar to list index element ? : " + str(res))
OutputThe original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Are row index element similar to list index element ? : True
Time Complexity: O(N*M)
Auxiliary Space: O(1)
Method #5: Using set intersection
- Initialize Matrix and target list as given in the problem statement.
- Iterate through each row in the matrix.
- Convert each row into a set using the set() method.
- Find the intersection of the set and target list using the & operator.
- Check if the length of the intersection is equal to the length of the target list. If yes, then the elements in the row are similar to the target list.
- If all rows pass the similarity test, set the result variable to True, else set it to False.
- Print the result.
Example:
Python3
# Python3 code to demonstrate working of
# Similar all elements as List in Matrix rows
# Using set intersection
# initializing Matrix and target list
test_list = [[1, 1, 1], [4, 4],
[3, 3, 3], [5, 5, 5, 5]]
tar_list = [1, 4, 3, 5]
# printing original list
print("The original list is : " + str(test_list))
res = True
for row in test_list:
if len(set(row) & set(tar_list)) != len(tar_list):
res = False
break
# printing result
print("Are row index element similar to list index element? : " + str(res))
OutputThe original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Are row index element similar to list index element? : False
Time complexity: O(n*m), where n is the number of rows and m is the maximum length of a row in the matrix.
Auxiliary space: O(m), where m is the maximum length of a row in the matrix.
Method 6: Using map() and zip() functions
Step-by-step approach:
- Use the map() function to iterate over each row in the test_list
- Use the zip() function to iterate over the elements in the row and their corresponding elements in the tar_list
- Use the all() function to check if all elements in the row are equal to their corresponding elements in the tar_list
- If any row does not meet the condition, set res to False and break out of the loop
- Print the result
Python3
# initializing Matrix
test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing tar_list
tar_list = [1, 4, 3, 5]
res = True
for row, tar in zip(test_list, tar_list):
if not all(map(lambda x, y: x == tar, row, [tar]*len(row))):
res = False
break
# printing result
print("Are row index element similar to list index element? : " + str(res))
OutputThe original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Are row index element similar to list index element? : True
Time complexity: O(n*m), where n is the number of rows in the matrix and m is the length of the largest row
Auxiliary space: O(m), as we are only storing the tar_list for comparison.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read