Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Kiểm tra Pangram (chứa toàn bộ chữ cái) trong Python

Pangram là câu chứa tất cả 26 chữ cái tiếng Anh (a-z) ít nhất 1 lần. Ví dụ kinh điển: "The quick brown fox jumps over the lazy dog".

Cách 1: Duyệt tập chữ cái (General)

import string

def is_pangram(text, alphabet=string.ascii_lowercase):
    text_lower = text.lower()
    for ch in alphabet:
        if ch not in text_lower:
            return False
    return True

# Test
s1 = "The Quick Brown Fox Jumps Over The Lazy Dog"
s2 = "TutorialsPoint TutorialsPoint"
print("Pangram" if is_pangram(s1) else "Not Pangram")  # Pangram
print("Pangram" if is_pangram(s2) else "Not Pangram")  # Not Pangram

Cách 2: Sử dụng Set (Pythonic, nhanh hơn)

import string

def is_pangram_set(text):
    return set(text.lower()) >= set(string.ascii_lowercase)

# Hoặc ngắn gọn inline
alphabet = set(string.ascii_lowercase)
print("Pangram" if set(s1.lower()) >= alphabet else "Not Pangram")
print("Pangram" if set(s2.lower()) >= alphabet else "Not Pangram")

Kết quả

Pangram
Not Pangram

So sánh

CáchĐộ phức tạpĐặc điểm
Loop alphabetO(26 * n) ≈ O(n)Dễ hiểu, dừng sớm nếu thiếu
Set >=O(n) build setNgắn gọn, pythonic, tạo set hoàn chỉnh

Mở rộng: Pangram cho tiếng Việt

vietnamese_alphabet = set("aăâbcdđeêghiklmnoôơpqrstuưvxy")
# Cần chuẩn hóa: bỏ dấu, lower, loại space/punctuation
import unicodedata
def normalize_vi(text):
    text = text.lower()
    text = unicodedata.normalize('NFD', text)
    text = ''.join(c for c in text if unicodedata.category(c) != 'Mn')  # bỏ dấu
    return ''.join(c for c in text if c.isalpha())

def is_pangram_vi(text):
    return set(normalize_vi(text)) >= vietnamese_alphabet

Kết luận

Dùng set(text.lower()) >= set(ascii_lowercase) cho ngắn gọn, hiệu quả. Cách loop phù hợp cho bài tập thuật toán, dừng sớm (short-circuit).