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
Code language: Python (python)

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" )
Code language: Python (python)

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
Code language: Python (python)

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
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Ajurna
Ajurna
1 year ago

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

John
1 year ago

This is really slick!