Python Counter| Find duplicate rows in a binary matrix
Last Updated :
29 Jul, 2022
Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicate of rows which are already present in the matrix.
Examples:
Input : [[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]]
Output : (1, 1, 0, 1, 0, 1)
(0, 0, 1, 0, 0, 1)
We have existing solution for this problem please refer Find duplicate rows in a binary matrix link. We can solve this problem very quickly in Python using Counter() method. Approach is very simple,
- Create a dictionary using counter method which will have rows as key and it’s frequency as value.
- Now traverse dictionary completely and print all rows which have frequency greater than 1.
Implementation:
Python3
from collections import Counter
def duplicate( input ):
input = map ( tuple , input )
freqDict = Counter( input )
for (row,freq) in freqDict.items():
if freq> 1 :
print (row)
if __name__ = = "__main__" :
input = [[ 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 ]]
duplicate( input )
|
Output
(1, 1, 0, 1, 0, 1)
(0, 0, 1, 0, 0, 1)
Share your thoughts in the comments
Please Login to comment...