import re
def is_isogram(phrase):
scrubbed = re.compile('[^a-zA-Z]').sub('', phrase).lower()
return len(set(scrubbed)) == len(scrubbed)
For this approach, regular expression, also known as a regex, is used to scrub the input phrase string.
- In the pattern of
[^a-zA-Z]
the brackets are used to define a character set that looks for characters which are nota
throughz
andA
throughZ
.
Note
If the first character of a character set is ^
, all the characters that are not in the rest of the character set will be matched.
This essentially matches any characters which are not in the English alphabet.
The pattern is passed to the compile()
method to construct a regular expression object.
- The
sub()
method is then called on the regex object. Thesub()
method replaces all non-alphabetic characters in the input phrase with an empty string. - The output of
sub()
is then chained as the input forlower()
. All of the letters are lowercased so that letters of different cases will become the same letter for comparison purposes, sinceA
anda
are considered to be the same letter. When the replacing and lowercasing is done, thescrubbed
variable will be a string having all alphabetic letters lowercased. - A
set
is constructed from thescrubbed
string and itslen
is compared with thelen
of the thescrubbed
string. Since aset
holds only unique values, the phrase will be an isogram if its number of unique letters is the same as its total number of letters. The function returns whether the number of unique letters equals the total number of letters. - For
Alpha
it would returnFalse
, becausea
is considered to repeatA
, so the number of unique letters inAlpha
is4
, and the total number of letters inAlpha
is5
. - For
Bravo
it would returnTrue
, since the number of unique letters inBravo
is5
, and the total number of letters inBravo
is5
.
4th Dec 2024
·
Found it useful?