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 PangramCá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 alphabet | O(26 * n) ≈ O(n) | Dễ hiểu, dừng sớm nếu thiếu |
| Set >= | O(n) build set | Ngắ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_alphabetKế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).