Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Test if all rows contain any common element with other Matrix
When working with matrices (lists of lists), you might need to check if all corresponding rows share at least one common element. This can be achieved using iteration with a flag variable to track the result.
Example
Below is a demonstration of testing row-wise common elements between two matrices −
matrix_1 = [[3, 16, 1], [2, 4], [4, 31, 31]]
matrix_2 = [[42, 16, 12], [42, 8, 12], [31, 7, 10]]
print("The first matrix is :")
print(matrix_1)
print("The second matrix is :")
print(matrix_2)
result = True
for idx in range(len(matrix_1)):
temp = False
for element in matrix_1[idx]:
if element in matrix_2[idx]:
temp = True
break
if not temp:
result = False
break
if result:
print("All rows contain common elements")
else:
print("Not all rows contain common elements")
The first matrix is : [[3, 16, 1], [2, 4], [4, 31, 31]] The second matrix is : [[42, 16, 12], [42, 8, 12], [31, 7, 10]] All rows contain common elements
How It Works
Two matrices are defined as lists of lists and displayed
A
resultvariable is initialized toTrueFor each row index, a temporary flag
tempis set toFalseEach element in the current row of the first matrix is checked against the corresponding row in the second matrix
If any common element is found,
tempbecomesTrueand the inner loop breaksIf no common element is found for any row,
resultbecomesFalseand the outer loop breaksThe final result indicates whether all rows have at least one common element
Alternative Using Set Intersection
A more Pythonic approach uses set intersection −
matrix_1 = [[3, 16, 1], [2, 4], [4, 31, 31]]
matrix_2 = [[42, 16, 12], [42, 8, 12], [31, 7, 10]]
# Check if all corresponding rows have common elements
result = all(set(matrix_1[i]) & set(matrix_2[i]) for i in range(len(matrix_1)))
if result:
print("All rows contain common elements")
else:
print("Not all rows contain common elements")
All rows contain common elements
Conclusion
Use nested loops with flag variables for explicit control, or leverage set intersection with all() for a more concise solution. Both approaches effectively test if all corresponding rows share common elements.
