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

  • Lambda Functions in Python

    Lambda Functions in Python Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression. Basic Syntax python lambda arguments: expression Simple Examples 1. Basic Lambda Function python # Regular function def add(x, y): return x + y # Equivalent lambda function add_lambda =…

  • append(), extend(), and insert() methods in Python lists

    append(), extend(), and insert() methods in Python lists, along with slicing where applicable. 1. append() Method Adds a single element to the end of the list. Examples: 2. extend() Method Adds multiple elements (iterable items) to the end of the list. Examples: 3. insert() Method Inserts an element at a specific position. Examples: Key Differences: Method Modifies List? Adds Single/Multiple Elements? Position append() ✅ Yes Single element (even if it’s a list) End…

  • File Handling in Python

    File Handling in Python File handling is a crucial aspect of programming that allows you to read from and write to files. Python provides built-in functions and methods to work with files efficiently. Basic File Operations 1. Opening a File Use the open() function to open a file. It returns a file object. python # Syntax: open(filename,…

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

  • Negative lookbehind assertion

    A negative lookbehind assertion in Python’s re module is a zero-width assertion that checks if a pattern is not present immediately before the current position. It is written as (?<!…). It’s the opposite of a positive lookbehind and allows you to exclude matches based on what precedes them. Similar to the positive lookbehind, the pattern…

  • 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…

Leave a Reply

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