5 Best Ways to Check if a String is Isogram or Not in Python

Rate this post

πŸ’‘ Problem Formulation: We aim to identify if a given string is an isogram in Python. An isogram is a word in which no letter occurs more than once. For instance, the input ‘dermatoglyphics’ should return true as it is an isogram, whereas ‘programming’ should return false.

Method 1: Using a Set for Comparison

One basic approach to determine if a string is an isogram involves comparing the length of the string with the length of the set of characters present in the string. Since sets contain unique elements, any discrepancy in lengths would indicate a repeating character.

Here’s an example:

def is_isogram(word):
    return len(word) == len(set(word.lower()))

print(is_isogram("dermatoglyphics")) # True
print(is_isogram("programming"))     # False

Output:

True
False

The function is_isogram takes a word and converts it to lowercase to maintain case insensitivity, then compares the length of the word with the length of the set made from its characters. If they are equal, the word is an isogram.

Method 2: Iterative Character Checking

This method iteratively checks each character against the rest of the string to ensure it doesn’t repeat. This is done by checking the occurrence of a character and ensuring it is no more than once.

Here’s an example:

def is_isogram(word):
    word = word.lower()
    for letter in word:
        if word.count(letter) > 1:
            return False
    return True

print(is_isogram("lumberjack"))     # True
print(is_isogram("environment"))    # False

Output:

True
False

The is_isogram function converts the word to lowercase and then iterates through each character, counting its occurrences in the word. If any character appears more than once, it returns false, indicating the word is not an isogram.

Method 3: Using a Dictionary for Character Frequency

An alternative approach involves creating a dictionary to keep a frequency count of each character. If any character has a count greater than one, the string is not an isogram.

Here’s an example:

def is_isogram(word):
    word = word.lower()
    char_frequency = {}

    for char in word:
        if char in char_frequency:
            return False
        char_frequency[char] = 1

    return True

print(is_isogram("isogram"))       # True
print(is_isogram("concede"))       # False

Output:

True
False

Within the is_isogram function, we iterate over the string, populating a dictionary with characters as keys. We immediately return False if a character is already present in the dictionary, otherwise, set its value to 1. This ensures an early exit if a duplicate is found.

Method 4: Using the Counter from collections

The Counter class from the collections module provides a convenient way to count occurrences of each element. An isogram will have all counts equal to one.

Here’s an example:

from collections import Counter

def is_isogram(word):
    word = word.lower()
    char_counts = Counter(word)
    return all(count == 1 for count in char_counts.values())

print(is_isogram("passport"))      # False
print(is_isogram("subdermatoglyphic")) # True

Output:

False
True

Following conversion to lowercase, the is_isogram function builds a Counter dictionary of character frequencies. It then checks if all character counts are 1, implying that the word is an isogram if true.

Bonus One-Liner Method 5: Pythonic Way Using Set

A concise one-liner Python solution utilizes the properties of sets and list comprehensions to verify isogram status. This method is very Pythonic and leverages the efficiency of set operations.

Here’s an example:

is_isogram = lambda word: len(word) == len(set(word.lower()))

print(is_isogram("pythonic"))   # True
print(is_isogram("examples"))   # False

Output:

True
False

The lambda function takes a word, converts it to lowercase for case insensitivity, and compares the length of the list to the set created from the list. This succinct approach is both elegant and efficient.

Summary/Discussion

Method 1: Set Comparison. Simple and efficient. Doesn’t work with characters outside A-Z (e.g., numbers, spaces).
Method 2: Iterative Character Checking. Easy to understand. Inefficient for long strings as it has a higher time complexity.
Method 3: Dictionary for Character Frequency. More control over handling of characters. Same inefficiency in time complexity as the previous method.
Method 4: Using Counter. Clean and concise. Relies on the standard library, which may be considered less educational for beginners.
Method 5: Pythonic One-Liner. Elegant and uses powerful features of Python. Can be less readable to those not familiar with Python’s concise style.