Thursday, July 4, 2024
HomeData ModellingData Structure & AlgorithmPython Counter| Find duplicate rows in a binary matrix

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.

Implementation:

Python3




# 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)


Output

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments