Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to check if the given string is pangram
In this article, we will learn how to check if a given string is a pangram using Python. A pangram is a sentence that contains every letter of the English alphabet at least once.
What is a Pangram?
A pangram is a sentence or series of words that uses every letter in the English alphabet collection. Famous examples include "The quick brown fox jumps over the lazy dog" and "Pack my box with five dozen liquor jugs".
Method 1: Using Manual Alphabet Check
We can check each letter of the alphabet to see if it exists in the input string ?
def ispangram(text):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in text.lower():
return False
return True
# Test the function
sentence = 'The five boxing wizards jump quickly.'
if ispangram(sentence):
print("Yes, it's a pangram")
else:
print("No, it's not a pangram")
Yes, it's a pangram
Method 2: Using Python's string Module
Python's string module provides a convenient way to access lowercase letters ?
import string
def ispangram_v2(text):
alphabet = set(string.ascii_lowercase)
return alphabet.issubset(set(text.lower()))
# Test the function
sentence = 'The quick brown fox jumps over the lazy dog'
print(f"'{sentence}' is pangram:", ispangram_v2(sentence))
sentence2 = 'Hello World'
print(f"'{sentence2}' is pangram:", ispangram_v2(sentence2))
'The quick brown fox jumps over the lazy dog' is pangram: True 'Hello World' is pangram: False
Method 3: Using Set Operations
We can use set operations to find missing letters efficiently ?
def ispangram_v3(text):
alphabet = set('abcdefghijklmnopqrstuvwxyz')
text_letters = set(text.lower())
missing = alphabet - text_letters
return len(missing) == 0
# Test with different examples
test_cases = [
'The five boxing wizards jump quickly.',
'Pack my box with five dozen liquor jugs',
'Python programming is fun',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
]
for text in test_cases:
result = ispangram_v3(text)
print(f"'{text[:30]}...' is pangram: {result}")
'The five boxing wizards jump ...' is pangram: True 'Pack my box with five dozen li...' is pangram: True 'Python programming is fun...' is pangram: False 'ABCDEFGHIJKLMNOPQRSTUVWXYZ...' is pangram: True
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Manual Check | O(26 × n) | O(1) | Simple understanding |
| String Module | O(n) | O(n) | Clean, readable code |
| Set Operations | O(n) | O(n) | Finding missing letters |
Conclusion
All three methods effectively check for pangrams. The set-based approaches are more efficient for longer texts, while the manual check method is easier to understand for beginners. Choose based on your specific needs and code readability preferences.
