Python Program to Check Pangram Phrases

import re

def panrgam(phrase):
    letters = re.sub(r'[^a-zA-Z]', '', phrase)
    letter_set = set(letters.lower())
    if len(letter_set) == 26:
        return True
    else:
        return False

str = 'The quick brown fox jumps over the lazy dog'

print(panrgam(str))

Python Program to Check Pangram Phrases

What is a Pangram?

A pangram is a sentence or phrase that contains every letter of the alphabet at least once.

Method 1: Using Set Operations

python

def is_pangram_set(phrase):
    """
    Check if a phrase is a pangram using set operations
    """
    # Convert to lowercase and remove non-alphabetic characters
    clean_phrase = ''.join(char.lower() for char in phrase if char.isalpha())
    
    # Check if the set of characters has exactly 26 elements
    return len(set(clean_phrase)) == 26

# Example usage
phrase = "The quick brown fox jumps over the lazy dog"
print(f"'{phrase}' is pangram: {is_pangram_set(phrase)}")

Method 2: Using ASCII Values

python

def is_pangram_ascii(phrase):
    """
    Check if a phrase is a pangram using ASCII values
    """
    # Convert to lowercase
    phrase = phrase.lower()
    
    # Check if all letters from a to z are present
    for char in range(ord('a'), ord('z') + 1):
        if chr(char) not in phrase:
            return False
    return True

Method 3: Using String Module

python

import string

def is_pangram_string_module(phrase):
    """
    Check if a phrase is a pangram using string module
    """
    # Convert to lowercase
    phrase = phrase.lower()
    
    # Check if all ASCII lowercase letters are in the phrase
    return all(char in phrase for char in string.ascii_lowercase)

Method 4: Using Counter (Collections Module)

python

from collections import Counter

def is_pangram_counter(phrase):
    """
    Check if a phrase is a pangram using Counter
    """
    # Count only alphabetic characters
    char_count = Counter(char.lower() for char in phrase if char.isalpha())
    
    # Check if we have exactly 26 unique letters
    return len(char_count) == 26

Complete Program with All Methods

python

import string
from collections import Counter

def is_pangram_set(phrase):
    """Check using set operations"""
    clean_phrase = ''.join(char.lower() for char in phrase if char.isalpha())
    return len(set(clean_phrase)) == 26

def is_pangram_ascii(phrase):
    """Check using ASCII values"""
    phrase = phrase.lower()
    for char in range(ord('a'), ord('z') + 1):
        if chr(char) not in phrase:
            return False
    return True

def is_pangram_string_module(phrase):
    """Check using string module"""
    phrase = phrase.lower()
    return all(char in phrase for char in string.ascii_lowercase)

def is_pangram_counter(phrase):
    """Check using Counter"""
    char_count = Counter(char.lower() for char in phrase if char.isalpha())
    return len(char_count) == 26

def check_pangram_all_methods(phrase):
    """
    Check pangram using all methods and return results
    """
    methods = [
        ("Set Operations", is_pangram_set),
        ("ASCII Values", is_pangram_ascii),
        ("String Module", is_pangram_string_module),
        ("Counter", is_pangram_counter)
    ]
    
    results = {}
    for method_name, method_func in methods:
        results[method_name] = method_func(phrase)
    
    return results

def get_missing_letters(phrase):
    """
    Return the missing letters if not a pangram
    """
    phrase = phrase.lower()
    all_letters = set(string.ascii_lowercase)
    present_letters = set(char for char in phrase if char.isalpha())
    missing_letters = sorted(all_letters - present_letters)
    return missing_letters

def display_pangram_info(phrase):
    """
    Display comprehensive information about the phrase
    """
    print(f"\nAnalyzing phrase: '{phrase}'")
    print("=" * 50)
    
    # Check with all methods
    results = check_pangram_all_methods(phrase)
    
    # Display results from each method
    for method, is_pangram in results.items():
        status = "✅ Pangram" if is_pangram else "❌ Not Pangram"
        print(f"{method:20}: {status}")
    
    # Check if all methods agree
    if all(results.values()):
        print("\n🎉 All methods confirm: This is a perfect pangram!")
    elif not any(results.values()):
        print("\n❌ All methods confirm: This is not a pangram.")
    else:
        print("\n⚠️  Methods disagree! (This shouldn't happen with proper implementation)")
    
    # Show missing letters if not pangram
    if not all(results.values()):
        missing = get_missing_letters(phrase)
        print(f"\nMissing letters ({len(missing)}): {', '.join(missing)}")
    
    # Show statistics
    clean_phrase = ''.join(char.lower() for char in phrase if char.isalpha())
    unique_letters = len(set(clean_phrase))
    print(f"\n📊 Statistics:")
    print(f"Total characters: {len(phrase)}")
    print(f"Alphabetic characters: {len(clean_phrase)}")
    print(f"Unique letters: {unique_letters}/26")
    print(f"Completion: {(unique_letters/26)*100:.1f}%")

def pangram_checker():
    """
    Interactive pangram checker
    """
    print("🔤 Pangram Checker")
    print("A pangram contains all letters of the alphabet (a-z)")
    print("Type 'quit' to exit\n")
    
    while True:
        phrase = input("Enter a phrase to check: ").strip()
        
        if phrase.lower() == 'quit':
            print("Goodbye! 👋")
            break
        
        if not phrase:
            print("Please enter a phrase!")
            continue
        
        display_pangram_info(phrase)
        
        # Ask if user wants to continue
        continue_check = input("\nCheck another phrase? (y/n): ").lower()
        if continue_check != 'y':
            print("Goodbye! 👋")
            break

# Example test cases
def test_pangrams():
    """Test various pangram examples"""
    test_cases = [
        # Perfect pangrams
        "The quick brown fox jumps over the lazy dog",
        "Pack my box with five dozen liquor jugs",
        "How vexingly quick daft zebras jump!",
        
        # Not pangrams
        "Hello world",
        "Python programming is fun",
        "This is not a pangram",
        
        # Edge cases
        "",  # Empty string
        "1234567890!@#$%^&*()",  # No letters
        "A" * 26,  # All same letter
    ]
    
    print("Testing Pangram Examples:")
    print("=" * 60)
    
    for phrase in test_cases:
        result = is_pangram_set(phrase)
        status = "✅ Pangram" if result else "❌ Not Pangram"
        print(f"{status}: '{phrase}'")
        
        if not result:
            missing = get_missing_letters(phrase)
            print(f"   Missing: {', '.join(missing)}")
        
        print("-" * 40)

if __name__ == "__main__":
    # Run interactive checker
    pangram_checker()
    
    # Uncomment to run test cases
    # test_pangrams()

Simple Version for Quick Use

python

def is_pangram_simple(phrase):
    """
    Simple one-line pangram checker
    """
    return len(set(char for char in phrase.lower() if char.isalpha())) == 26

# Quick usage examples
phrases = [
    "The quick brown fox jumps over the lazy dog",
    "Hello world",
    "Pack my box with five dozen liquor jugs"
]

for phrase in phrases:
    result = is_pangram_simple(phrase)
    print(f"'{phrase}' -> {'Pangram' if result else 'Not Pangram'}")

How to Use:

  1. Run the interactive checker:

bash

python pangram_checker.py
  1. Test specific phrases:

python

phrase = "Your phrase here"
print(f"Is pangram: {is_pangram_set(phrase)}")
  1. Get missing letters:

python

missing = get_missing_letters("Hello World")
print(f"Missing letters: {missing}")

Features:

  • ✅ Multiple implementation methods
  • ✅ Missing letters identification
  • ✅ Statistics and analysis
  • ✅ Interactive mode
  • ✅ Test cases included
  • ✅ Error handling
  • ✅ Case insensitive
  • ✅ Ignores numbers and symbols

Example Output:

text

Analyzing phrase: 'The quick brown fox jumps over the lazy dog'
==================================================
Set Operations       : ✅ Pangram
ASCII Values         : ✅ Pangram
String Module        : ✅ Pangram
Counter              : ✅ Pangram

🎉 All methods confirm: This is a perfect pangram!

📊 Statistics:
Total characters: 43
Alphabetic characters: 33
Unique letters: 26/26
Completion: 100.0%

This program provides a comprehensive solution for checking pangram phrases with multiple approaches and detailed analysis!

Similar Posts

  • Top Programming Languages and Tools Developed Using Python

    Python itself is not typically used to develop other programming languages, as it is a high-level language designed for general-purpose programming. However, Python has been used to create domain-specific languages (DSLs), tools for language development, and educational languages. Here are some examples: 1. Hy 2. Coconut Description: A functional programming language that compiles to Python. It adds…

  • Python Nested Lists

    Python Nested Lists: Explanation & Examples A nested list is a list that contains other lists as its elements. They are commonly used to represent matrices, tables, or hierarchical data structures. 1. Basic Nested List Creation python # A simple 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]…

  • re module

    The re module is Python’s built-in module for regular expressions (regex). It provides functions and methods to work with strings using pattern matching, allowing you to search, extract, replace, and split text based on complex patterns. Key Functions in the re Module 1. Searching and Matching python import re text = “The quick brown fox jumps over the lazy dog” # re.search()…

  • Data hiding

    Data hiding in Python OOP is the concept of restricting access to the internal data of an object from outside the class. 🔐 It’s a way to prevent direct modification of data and protect the object’s integrity. This is typically achieved by using a naming convention that makes attributes “private” or “protected.” 🔒 How Data…

  •  index(), count(), reverse(), sort()

    Python List Methods: index(), count(), reverse(), sort() Let’s explore these essential list methods with multiple examples for each. 1. index() Method Returns the index of the first occurrence of a value. Examples: python # Example 1: Basic usage fruits = [‘apple’, ‘banana’, ‘cherry’, ‘banana’] print(fruits.index(‘banana’)) # Output: 1 # Example 2: With start parameter print(fruits.index(‘banana’, 2)) # Output: 3 (starts searching…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

Leave a Reply

Your email address will not be published. Required fields are marked *