The task is to check if astring is apangramwhich means it includes every letter of the English alphabet at least once. In this article, we’ll look at different ways to check if the string contains all 26 letters.
Using Bitmasking
Bitmasking uses a number where each bit represents a letter in the alphabet. It updates the bits as it finds letters in the string and checks if all 26 letters are present.
Example:
Python# Input strings="The quick brown fox jumps over the lazy dog"# Initialize bitmask for tracking found lettersf=0# Loop through each character in lowercase stringforcharins.lower():ifchar.isalpha():# Check if the character is alphabeticf|=1<<(ord(char)-ord('a'))# Set corresponding bit for letteriff==(1<<26)-1:# All letters foundprint(True)# It's a pangrambreakelse:print(False)# Not a pangram
Using sets
We can usesets
to store unique characters and perform fast checks.string.ascii_lowercase
gives astring of all lowercase letters, which can be turned into a set for easy comparison.
Example:
Pythonimportstring# Input stringa="The quick brown fox jumps over the lazy dog"# Create set of all lowercase English lettersb=set(string.ascii_lowercase)# Convert input text to lowercase# Create a set of characterss=set(a.lower())# Check if `s` contains all letters of `b`res=b<=sprint(res)
Using all()
all() function checks if every condition in a list is true. Here, it checks if every letter of the alphabet is in the given text and returns True only if all letters are found.
Example:
Pythonimportstring# Input texts="Python is great"# Check if all letters are in `s`res=all(letterins.lower()forletterinstring.ascii_lowercase)print(res)
Using count()
count() method checks how many times each letter appears in the string. It repeatedly does this for all letters of the alphabet to see if the string contains every letter.
Example:
Pythonimportstring# Input texts="The quick brown fox jumps over the lazy dog."# Check if each letter of the alphabet appears in `t`forletterinstring.ascii_lowercase:ifs.lower().count(letter)==0:print(False)breakelse:print(True)
Explanation:
- string.ascii_lowercase provides all lowercase letters to check against the input string.
- s.lower().count(letter) This checks if each letter appears in `s`, prints False if any letter is missing.