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

  • Linear vs. Scalar,Homogeneous vs. Heterogeneous 

    Linear vs. Scalar Data Types in Python In programming, data types can be categorized based on how they store and organize data. Two important classifications are scalar (atomic) types and linear (compound) types. 1. Scalar (Atomic) Data Types 2. Linear (Compound/Sequential) Data Types Key Differences Between Scalar and Linear Data Types Feature Scalar (Atomic) Linear (Compound) Stores Single…

  • Method overriding

    Method overriding is a key feature of object-oriented programming (OOP) and inheritance. It allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class). When a method is called on an object of the child class, the child’s version of the method is…

  • Python Modules: Creation and Usage Guide

    Python Modules: Creation and Usage Guide What are Modules in Python? Modules are simply Python files (with a .py extension) that contain Python code, including: They help you organize your code into logical units and promote code reusability. Creating a Module 1. Basic Module Creation Create a file named mymodule.py: python # mymodule.py def greet(name): return f”Hello, {name}!”…

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

  • Vs code

    What is VS Code? 💻 Visual Studio Code (VS Code) is a free, lightweight, and powerful code editor developed by Microsoft. It supports multiple programming languages (Python, JavaScript, Java, etc.) with: VS Code is cross-platform (Windows, macOS, Linux) and widely used for web development, data science, and general programming. 🌐📊✍️ How to Install VS Code…

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

Leave a Reply

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