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

Python: ลบคำที่ซ้ำกันระหว่างสองสตริง (Uncommon Words)

บทนำ

โจทย์: หาคำที่ปรากฏในสตริงใดสตริงหนึ่งเพียงอย่างเดียว (ไม่ปรากฏในทั้งสอง) ใช้ dictionary นับความถี่รวม แล้วกรองค่าที่มี count == 1

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


def uncommon_words(str1, str2):
    """คืนลิสต์คำที่ปรากฏในสตริงใดสตริงหนึ่งอย่างเดียว"""
    word_count = {}
    
    # นับคำในสตริงแรก
    for word in str1.split():
        word_count[word] = word_count.get(word, 0) + 1
    
    # นับคำในสตริงที่สอง
    for word in str2.split():
        word_count[word] = word_count.get(word, 0) + 1
    
    # กรองคำที่มี count == 1
    return [word for word, count in word_count.items() if count == 1]

# ทดสอบ
str1 = "Python is fun"
str2 = "Python is fun to learn"

print(f"สตริง 1: '{str1}'")
print(f"สตริง 2: '{str2}'")

result = uncommon_words(str1, str2)
print(f"คำที่ไม่ซ้ำ: {result}")

ผลลัพธ์


สตริง 1: 'Python is fun'
สตริง 2: 'Python is fun to learn'
คำที่ไม่ซ้ำ: ['to', 'learn']

คำอธิบาย


# นับรวม:
Python: 2 (อยู่ในทั้งสอง)
is: 2 (อยู่ในทั้งสอง)
fun: 2 (อยู่ในทั้งสอง)
to: 1 (อยู่แค่ str2) ← เก็บ
learn: 1 (อยู่แค่ str2) ← เก็บ

วิธีทางเลือก: ใช้ Set Operations


def uncommon_words_set(str1, str2):
    """ใช้ set symmetric difference"""
    set1 = set(str1.split())
    set2 = set(str2.split())
    # symmetric difference: อยู่ในฝั่งเดียว
    return list(set1 ^ set2)

print(uncommon_words_set(str1, str2))  # ['learn', 'to']

เปรียบเทียบวิธี

วิธีรักษาลำดับนับความถี่Case sensitive
Dictionary count❌ (Python 3.7+ รักษา insertion order)✅✅
Set ^ (symmetric diff)❌❌ (เฉพาะมี/ไม่มี)✅
Counter + filter❌✅✅

ฟังก์ชันครบถ้วน (รองรับ case-insensitive, punctuation)


import re
from collections import Counter

def uncommon_words_advanced(str1, str2, ignore_case=True, remove_punct=True):
    def normalize(s):
        if remove_punct:
            s = re.sub(r'[^\w\s]', '', s)
        if ignore_case:
            s = s.lower()
        return s.split()
    
    words1 = normalize(str1)
    words2 = normalize(str2)
    
    freq = Counter(words1 + words2)
    return [word for word, count in freq.items() if count == 1]

# ทดสอบ
print(uncommon_words_advanced("Python is fun!", "Python is fun, to learn."))
# ['to', 'learn']

สรุป

ใช้ set1 ^ set2 (symmetric difference) สำหรับหาคำที่ไม่ซ้ำแบบง่าย (O(n)) ใช้ Counter เมื่อต้องการนับความถี่หรือจัดการ punctuation/case