- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Check Similar elements in Matrix rows
When it is required to check for similar elements in a matrix row, a method is defined that take a matrix as parameter. The map method is used to covert the matrix to a tuple. The matrix values are iterated over and if the frequency is greater than 1, it is displayed on the console.
Example
Below is a demonstration of the same
from collections import Counter def find_dupes(my_matrix): my_matrix = map(tuple,my_matrix) freq_dict = Counter(my_matrix) for (row,freq) in freq_dict.items(): if freq>1: print (row) my_matrix = [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]] print("The matrix is :") print(my_matrix) print("The result is :") find_dupes(my_matrix)
Output
The matrix is : [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]] The result is : (1, 1, 0, 1, 0, 1) (0, 0, 1, 0, 0, 1)
Explanation
The required packages are imported.
A method named ‘find_dupes’ is defined that takes a matrix as a parameter.
The ‘map’ method is used to convert the matrix to a tuple.
The counter method is used to get the count of every value in the matrix.
This is stored in a dictionary.
The dictionary items are iterated over.
If the frequency of any element is greater than 1, it is displayed on the console.
Outside the method, a matrix (technically a list of list) is defined and is displayed on the console.
The method is called by passing the required parameter.
The result is displayed on the console.