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

Permutations แบบไม่ซ้ำ (Distinct) ของสตริงด้วย itertools ใน Python

หา permutations ที่ไม่ซ้ำกันของสตริงที่มีตัวอักษรซ้ำ ใช้ itertools.permutations + set

ตัวอย่าง

Input: "xyxxz", k=12
Output: 12 permutations แรกที่ไม่ซ้ำ

โค้ด

from itertools import permutations

def distinct_permutations(s, k):
    # เรียงตัวอักษรก่อน เพื่อให้ permutations เรียงลำดับ
    sorted_chars = sorted(s)
    perm_gen = permutations(sorted_chars)
    
    seen = set()
    count = 0
    while count < k:
        try:
            p = ''.join(next(perm_gen))
        except StopIteration:
            break
        if p not in seen:
            seen.add(p)
            print(p)
            count += 1

# ทดสอบ
distinct_permutations("xyxxz", 12)

ผลลัพธ์

xxxyz
xxxzy
xxyxz
xxyzx
xxzxy
xxzyx
xyxxz
xyxzx
xyzxx
xzxxy
xzxyx
xzyxx

หมายเหตุ

  • sorted(s) ทำให้ permutations ออกมาเรียง lexicographic
  • set กรองซ้ำ
  • ถ้าต้องการทั้งหมด ใช้ set(permutations(sorted(s))) แล้ว join

สรุป

itertools + set + sorted ให้ distinct permutations ที่เรียงลำดับ