Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Tổ hợp phổ biến nhất trong ma trận

Để tìm các tổ hợp (combinations) xuất hiện nhiều nhất trong ma trận (danh sách các danh sách), ta dùng itertools.combinations, Counter và sắp xếp.

Ví dụ

Minh họa:

from collections import Counter
from itertools import combinations

my_list = [[31, 25, 77, 82], [96, 15, 23, 32]]
print("Ma trận:")
print(my_list)

my_counter = Counter()
for elem in my_list:
    if len(elem) < 2:
        continue
    elem.sort()
    for size in range(2, len(elem) + 1):
        for comb in combinations(elem, size):
            my_counter[comb] += 1

max_count = my_counter.most_common(1)[0][1]
my_result = [comb for comb, cnt in my_counter.items() if cnt == max_count]
print("Tổ hợp phổ biến nhất:")
print(my_result)

Kết quả

Ma trận: [[31, 25, 77, 82], [96, 15, 23, 32]]
Tổ hợp phổ biến nhất: [(15, 23, 32, 96), (25, 31), (25, 82), (15, 32), (23, 32), (15, 32, 96), (25, 31, 82), (15, 23), (25, 77), (15, 23, 32), (25, 77, 82), (32, 96), (31, 77, 82), (15, 96), (31, 77), (23, 96), (25, 31, 77, 82), (31, 82), (77, 82), (23, 32, 96), (15, 23, 96), (25, 31, 77)]

Giải thích

  • Import Counter và combinations.
  • Duyệt từng hàng, bỏ qua hàng độ dài < 2.
  • Sắp xếp hàng, sinh mọi tổ hợp kích thước 2..n, đếm bằng Counter.
  • Lấy tổ hợp có số lần xuất hiện lớn nhất.