
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Test if All Rows Contain Common Element with Other Matrix in Python
When it is required to test if all rows contain any common element with other matrix, a simple iteration and a flag value are used.
Example
Below is a demonstration of the same
my_list_1 = [[3, 16, 1], [2, 4], [4, 31, 31]] my_list_2 = [[42, 16, 12], [42, 8, 12], [31, 7, 10]] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) my_result = True for idx in range(0, len(my_list_1)): temp = False for element in my_list_1[idx]: if element in my_list_2[idx]: temp = True break if not temp : my_result = False break if(temp == True): print("The two matrices contain common elements") else: print("The two matrices don't contain common elements")
Output
The first list is : [[3, 16, 1], [2, 4], [4, 31, 31]] The second list is : [[42, 16, 12], [42, 8, 12], [31, 7, 10]] The two matrices don't contain common elements
Explanation
Two lists of lists are defined and are displayed on the console.
A variable is set to Boolean ‘True’.
The first list is iterated and a temporary variable is set to Boolean ‘False’.
If the element is present in the second list, then the temporary variable is set to Boolean ‘True’.
The control breaks out of the loop.
If the temporary variable is False outside the loop, the control breaks out of the loop.
In the end, based on the value of the temporary variable, the relevant message is displayed on the console.
Advertisements