Python Counter| Find duplicate rows in a binary matrix

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,

  1. Create a dictionary using counter method which will have rows as key and it’s frequency as value.
  2. Now traverse dictionary completely and print all rows which have frequency greater than 1.
filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to find duplicate rows in a binary matrix
from collections import Counter
  
def duplicate(input):
  
     # since lists are unhasable for counter method
     # because lists are mutable so first we will cast
     # each row (list) into tuple
     input = map(tuple,input)
  
     # now create dictionary
     freqDict = Counter(input)
  
     # print all rows having frequency greater than 1
     for (row,freq) in freqDict.items():
          if freq>1:
              print (row)
  
# Driver program
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)

chevron_right


Output:

(1, 1, 0, 1, 0, 1)
(0, 0, 1, 0, 0, 1)


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.