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

หาคำที่ไม่ซ้ำกัน (Uncommon Words) จากสองสตริงใน Python

โจทย์: กำหนดสองสตริง หาคำที่ปรากฏในสตริงใดสตริงหนึ่งเพียงอย่างเดียว (ไม่ปรากฏในทั้งสอง)

ตัวอย่าง

A = "Tutorials point"
B = "Python on Tutorials point"
Output: ["Python", "on"]

อัลกอริทึม: Frequency Count

  1. นับความถี่คำในทั้งสองสตริงรวมกัน
  2. คืนคำที่มีความถี่ = 1

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

def find_uncommon_words(A, B):
    count = {}
    
    # นับคำใน A
    for word in A.split():
        count[word] = count.get(word, 0) + 1
    
    # นับคำใน B
    for word in B.split():
        count[word] = count.get(word, 0) + 1
    
    # คืนคำที่มีความถี่ 1
    return [word for word, freq in count.items() if freq == 1]

# ทดสอบ
A = "Tutorials point"
B = "Python on Tutorials point"
print("The uncommon words in strings are:", find_uncommon_words(A, B))
# Output: ['Python', 'on']

ผลลัพธ์

The uncommon words in strings are: ['Python', 'on']

วิธี Alternative: Counter

from collections import Counter

def find_uncommon_words(A, B):
    combined = A.split() + B.split()
    freq = Counter(combined)
    return [word for word, count in freq.items() if count == 1]

ความซับซ้อน: Time O(n+m), Space O(n+m)