Check if Isogram using Python

1 min read 273 words

The challenge

An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.

is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case

Test cases

Test.assert_equals(is_isogram("Dermatoglyphics"), True )
Test.assert_equals(is_isogram("isogram"), True )
Test.assert_equals(is_isogram("aba"), False, "same chars may not be adjacent" )
Test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" )
Test.assert_equals(is_isogram("isIsogram"), False )
Test.assert_equals(is_isogram(""), True, "an empty string is a valid isogram" )

The solution in Python

First pass, using a dictionary (dict):

def is_isogram(string):
    # if not a Str then return False
    if type(string) is not str:
        return False
    
    # if empty then return True
    if len(string)==0:
        return True
    
    # store characters
    db = {}
    
    # loop through the string, but lowercase it first
    for char in string.lower():
        # if it's already been seen, then return False
        if char in db:
            return False
        else:
            # otherwise add to the db
            db[char] = 1
            
    # return True if not failed
    return True

Make it a bit more efficient by using a set:

def is_isogram(string):
    # if not a Str then return False
    if type(string) is not str:
        return False
    
    # if empty then return True
    if len(string)==0:
        return True
    
    # store characters
    db = set()
    
    # loop through the string, but lowercase it first
    for char in string.lower():
        # if it's already been seen, then return False
        if char in db:
            return False
        else:
            # otherwise add to the db
            db.append(char)
            
    # return True if not failed
    return True
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags