Check if Isogram using Python

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:
5 1 vote
Article Rating
Subscribe
Notify of
guest
3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Ajurna
Ajurna
1 month ago

why are you using a dict when a set would be more appropriate?

John
1 month ago

This is really slick!