Cho ma trận nhị phân chỉ chứa 0 và 1, nhiệm vụ tìm hàng trùng lặp và in ra.
Python cung cấp Counter() method dùng ở đây.
Ví dụ
Input: 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 Output: (1, 1, 1, 1) (0, 0, 0, 0)
Thuật toán
Bước 1: Tạo ma trận nhị phân, chỉ có 0 và 1. Bước 2: Key là hàng, value là tần suất. List mutable nên trước tiên cast từng hàng (list) thành tuple. Bước 3: Tạo dictionary dùng Counter method. Bước 4: Duyệt dictionary hoàn toàn. Bước 5: In tất cả hàng có tần suất > 1.
Ví dụ mã
# Hàm tìm hàng trùng lặp trong ma trận nhị phân
from collections import Counter
def binarymatrix(A):
A = map(tuple, A)
dic = Counter(A)
print("Duplicate rows of Binary Matrix ::>")
for (i, j) in dic.items():
if j > 1:
print(i)
# Driver program
if __name__ == "__main__":
A = []
n = int(input("Enter n for n x n matrix: "))
print("Enter the element ::>")
for i in range(n):
row = []
for j in range(n):
row.append(int(input()))
A.append(row)
print(A)
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print()
binarymatrix(A)
Kết quả
Enter n for n x n matrix: 4 Enter the element ::> 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 [[1, 1, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]] Display Array In Matrix Form 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 Duplicate rows of Binary Matrix ::> (1, 1, 1, 1) (0, 0, 0, 0)