Python program to find duplicate rows in a binary matrix

In this article, we will learn how to find duplicate rows in a binary matrix in Python. A matrix is said to binary matrix if it only contains 0’s, 1’s as its elements.

Example

Input: matrix = [[1, 0, 1, 1],
                 [0, 1, 0, 1],
                 [1, 0, 1, 1],
                 [1, 1, 1, 1]]
Output: (1, 0, 1, 1)

We are going to solve this problem using the Counter() method.

What is Python Counter?

Python Counter takes in information such as lists, tuples, dictionaries, strings, etc., which are completely repeatable objects, and outputs the count of each component. Python counter can be imported by using the command

from collections import Counter

Counter Example

from collections import Counter
arr = [1, 2, 3, 4, 3, 5, 2, 1, 4]
print(Counter(arr))

Output

Counter({1: 2, 2: 2, 3: 2, 4: 2, 5: 1})

Find duplicate rows in a binary matrix in Python

1. Firstly, create a dictionary using Counters that stores rows as key and their frequency as value.

2. Now print the rows whose frequency greater than 1.

from collections import Counter
def duplicate(matrix):
    matrix = map(tuple, matrix)
    freqs = Counter(matrix)
    for (row, freq) in freqs.items():
        if (freq>1):
            print(row)
matrix = [[1, 1, 0, 1, 0],
          [0, 1, 0, 1, 1],
          [1, 1, 0, 1, 0],
          [1, 1, 1, 1, 1],
          [0, 1, 0, 1, 1]]
duplicate(matrix)

Output

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

Also, read

Leave a Reply

Your email address will not be published.