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

หาคำที่เป็นไปได้จากชุดตัวอักษรที่กำหนดใน Python

ในบทช่วยสอนนี้ เราจะหาคำทั้งหมดที่สามารถสร้างได้จากชุดตัวอักษรที่กำหนด (แต่ละตัวอักษรใช้ได้ตามจำนวนที่มีอยู่)

ตัวอย่าง

Input: words = ["hi", "hello", "bye", "good"]
       characters = ["h", "i", "b", "y", "e"]
Output: hi bye

อัลกอริทึม

1. กำหนด words list และ characters list
2. ฟังก์ชัน char_count(word): คืน dictionary นับความถี่ตัวอักษร
3. วนลูป words:
   3.1 flag = 1
   3.2 หา char_count ของ word
   3.3 วนลูป char_count: ถ้าตัวอักษรไม่อยู่ใน characters หรือ จำนวนมากกว่าที่มี → flag = 0
   3.4 ถ้า flag == 1 → พิมพ์ word

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

words = ["hi", "hello", "bye", "good"]
characters = ["h", "i", "b", "y", "e"]

def char_count(word):
    char_count = {}
    for char in word:
        char_count[char] = char_count.get(char, 0) + 1
    return char_count

for word in words:
    flag = 1
    chars = char_count(word)
    for key in chars:
        if key not in characters:
            flag = 0
        elif characters.count(key) != chars[key]:
            flag = 0
    if flag == 1:
        print(word)

ผลลัพธ์

hi
bye

วิธี替代: ใช้ Counter

from collections import Counter

words = ["hi", "hello", "bye", "good"]
characters = ["h", "i", "b", "y", "e"]
char_counter = Counter(characters)

for word in words:
    word_counter = Counter(word)
    if all(word_counter[char] <= char_counter.get(char, 0) for char in word_counter):
        print(word)

สรุป

ตรวจสอบว่าแต่ละคำใช้ตัวอักษรไม่เกินจำนวนที่มีใน character pool ใช้ Counter ทำให้โค้ดสั้นและอ่านง่ายกว่า หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น