Python มี Built-in Package itertools สำหรับหา Permutation และ Combination ของ Sequence ได้อย่างง่ายดาย
อัลกอริทึมพื้นฐาน
- Import
itertools - ใช้
permutations()หรือcombinations()กับ Sequence - กำหนดความยาว (r) ได้ (Optional)
- Iterate หรือแปลงเป็น List เพื่อดูผลลัพธ์
Permutation (ลำดับสำคัญ)
จัดเรียงสิ่งของโดยคำนึงถึงลำดับ
ตัวอย่างที่ 1: Permutation ทั้งหมดของ 3 Items
from itertools import permutations
seq = permutations(['a', 'b', 'c'])
for p in seq:
print(p)
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
ตัวอย่างที่ 2: Permutation ความยาว 2 จาก 6 Items
from itertools import permutations
seq = permutations(['p', 'y', 't', 'h', 'o', 'n'], 2)
for p in seq:
print(p)
('p', 'y') ('p', 't') ('p', 'h') ('p', 'o') ('p', 'n')
('y', 'p') ('y', 't') ('y', 'h') ('y', 'o') ('y', 'n')
('t', 'p') ('t', 'y') ('t', 'h') ('t', 'o') ('t', 'n')
('h', 'p') ('h', 'y') ('h', 't') ('h', 'o') ('h', 'n')
('o', 'p') ('o', 'y') ('o', 't') ('o', 'h') ('o', 'n')
('n', 'p') ('n', 'y') ('n', 't') ('n', 'h') ('n', 'o')
Combination (ลำดับไม่สำคัญ)
เลือกสิ่งของโดยไม่คำนึงถึงลำดับ
ตัวอย่างที่ 1: Combination ความยาว 5 จาก 6 Items
from itertools import combinations
combi = combinations(['p', 'y', 't', 'h', 'o', 'n'], 5)
for c in combi:
print(c)
('p', 'y', 't', 'h', 'o')
('p', 'y', 't', 'h', 'n')
('p', 'y', 't', 'o', 'n')
('p', 'y', 'h', 'o', 'n')
('p', 't', 'h', 'o', 'n')
('y', 't', 'h', 'o', 'n')
ตัวอย่างที่ 2: Combinations with Replacement (ซ้ำได้)
from itertools import combinations_with_replacement
combi = combinations_with_replacement(['p', 'y', 't', 'h', 'o', 'n'], 2)
for c in combi:
print(c)
('p', 'p') ('p', 'y') ('p', 't') ('p', 'h') ('p', 'o') ('p', 'n')
('y', 'y') ('y', 't') ('y', 'h') ('y', 'o') ('y', 'n')
('t', 't') ('t', 'h') ('t', 'o') ('t', 'n')
('h', 'h') ('h', 'o') ('h', 'n')
('o', 'o') ('o', 'n')
('n', 'n')
สรุปฟังก์ชัน itertools ที่เกี่ยวข้อง
| Function | คำอธิบาย | ลำดับสำคัญ? |
|---|---|---|
permutations(iterable, r) | เรียงสับเปลี่ยน ความยาว r | ใช่ |
combinations(iterable, r) | เลือกแบบไม่ซ้ำ ความยาว r | ไม่ |
combinations_with_replacement(iterable, r) | เลือกแบบซ้ำได้ ความยาว r | ไม่ |
product(*iterables, repeat) | Cartesian Product | ใช่ |
สูตรคณิตศาสตร์
- Permutation: P(n, r) = n! / (n-r)!
- Combination: C(n, r) = n! / (r! × (n-r)!)
- Combination with Replacement: C(n+r-1, r)