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

  • Strings in Python Indexing,Traversal

    Strings in Python and Indexing Strings in Python are sequences of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). They are immutable sequences of Unicode code points used to represent text. String Characteristics Creating Strings python single_quoted = ‘Hello’ double_quoted = “World” triple_quoted = ”’This is…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

  • Create a User-Defined Exception

    A user-defined exception in Python is a custom error class that you create to handle specific error conditions within your code. Instead of relying on built-in exceptions like ValueError, you define your own to make your code more readable and to provide more specific error messages. You create a user-defined exception by defining a new…

  • file properties and methods

    1. file.closed – Is the file door shut? Think of a file like a door. file.closed tells you if the door is open or closed. python # Open the file (open the door) f = open(“test.txt”, “w”) f.write(“Hello!”) print(f.closed) # Output: False (door is open) # Close the file (close the door) f.close() print(f.closed) # Output: True (door is…

  • Python Variables: A Complete Guide with Interview Q&A

    Here’s a detailed set of notes on Python variables that you can use to explain the concept to your students. These notes are structured to make it easy for beginners to understand. Python Variables: Notes for Students 1. What is a Variable? 2. Rules for Naming Variables Python has specific rules for naming variables: 3….

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

Leave a Reply

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