Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python หาแถวซ้ำใน Binary Matrix ด้วย Counter


หาแถวซ้ำใน binary matrix (มีแค่ 0,1) โดยใช้ collections.Counter นับความถี่แต่ละแถว (แปลงแถวเป็น tuple เพื่อ hash ได้)

ตัวอย่าง

Input 4x4:
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)

อัลกอริทึม

  1. สร้าง binary matrix
  2. แปลงแต่ละแถวเป็น tuple แล้ว Counter
  3. พิมพ์แถวที่ frequency > 1

โค้ดตัวอย่าง

from collections import Counter

def binarymatrix(A):
    A = map(tuple, A)
    dic = Counter(A)
    print("Duplicate rows of Binary Matrix:")
    for row, freq in dic.items():
        if freq > 1:
            print(row)

# ... input matrix code ...
binarymatrix(A)

ผลลัพธ์

Duplicate rows of Binary Matrix:
(1, 1, 1, 1)
(0, 0, 0, 0)