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

สร้างการเรียงสับเปลี่ยน (Permutations) ของคำในประโยคด้วย itertools.permutations

ใช้ itertools.permutations() เพื่อสร้างการเรียงสับเปลี่ยนทั้งหมดของคำในประโยค โดยแยกคำด้วย space แล้วหา permutations ของลิสต์คำ

ตัวอย่างโค้ด

from itertools import permutations

def calculate_permutations(sentence):
    words = sentence.split()
    perms = permutations(words)
    
    print(f"ประโยคต้นฉบับ: {sentence}")
    print("ทุกการเรียงสับเปลี่ยนที่เป็นไปได้:")
    for i, perm in enumerate(perms, 1):
        print(f"{i}. {' '.join(perm)}")

# ทดสอบ
calculate_permutations("hi there")

ผลลัพธ์

ประโยคต้นฉบับ: hi there
ทุกการเรียงสับเปลี่ยนที่เป็นไปได้:
1. hi there
2. there hi

สำหรับ 2 คำ จะมี 2! = 2 แบบ สำหรับ n คำ จะมี n! แบบ อาจเยอะมากถ้าคำมาก