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

Python - หาการรวม (Combination) ที่พบบ่อยที่สุดในแมทริกซ์


ตัวอย่าง

โค้ดด้านล่างใช้ Counter และ combinations จาก itertools เพื่อหาการรวมของสมาชิกในแต่ละแถวของแมทริกซ์ที่พบบ่อยที่สุด (ทุกขนาดการรวมตั้งแต่ 2 ถึงความยาวแถว)

from collections import Counter
from itertools import combinations
my_list = [[31, 25, 77, 82], [96, 15, 23, 32]]
print("The list is :")
print(my_list)
my_result = 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_result[comb] += 1
my_result = [elem for elem, my_count in my_result.items() if my_count == my_result.most_common(1)[0][1]]
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [[31, 25, 77, 82], [96, 15, 23, 32]]
The result is : [(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)]

คำอธิบาย

  • import Counter และ combinations

  • กำหนดแมทริกซ์ (ลิสต์ของลิสต์) และแสดงผล

  • สร้าง Counter ว่าง

  • วนลูปแต่ละแถว: ถ้าความยาว < 2 ข้ามไป, มิฉะนั้นเรียงลำดับ แล้ววนหาการรวมทุกขนาด (2 ถึง n) และนับความถี่ใน Counter

  • กรองเฉพาะการรวมที่มีความถี่เท่ากับค่าสูงสุด (most_common)

  • แสดงผลลัพธ์