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

Permutation และ Combination ใน Python (itertools)

Python มี Built-in Package itertools สำหรับหา Permutation และ Combination ของ Sequence ได้อย่างง่ายดาย

อัลกอริทึมพื้นฐาน

  1. Import itertools
  2. ใช้ permutations() หรือ combinations() กับ Sequence
  3. กำหนดความยาว (r) ได้ (Optional)
  4. 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)