Write a program that checks if a word supplied as the argument is an Isogram. An Isogram is a word in which no letter occurs more than once. Create a function called is_isogram
that takes one argument, a word
to test if it's an isogram. This method should return a tuple/list/array
of the word and a boolean
indicating whether it is an isogram. If the argument supplied is an empty string, return
the argument and False
, ie (argument, False)
. If the argument supplied is not a string, raise a TypeError
with the message 'Argument should be a string'
.
The challenge here is to write three unique solutions, using whichever language you like. However, you must maintain the specified identifiers and error messages in the question and use the least possible number of characters to solve the problem. White space will be ignored for readability's sake.
Last active
January 14, 2021 16:28
-
-
Save allengblack/330975d1406a6aea246df0bb0eaac2f6 to your computer and use it in GitHub Desktop.
Find the Isogram
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#using dictionaries | |
#191 | |
def is_isogram(w): | |
if type(w) != str: | |
raise TypeError('Argument should be a string') | |
if not w: | |
return w, False | |
c = [k for k in w] | |
d = {} | |
for i in range(len(c)): | |
if c[i] in d: | |
return w, False | |
else: | |
d[c[i]] = '' | |
return w, True | |
#using lists | |
#207 | |
def is_isogram(w): | |
if type(w) != str: | |
raise TypeError('Argument should be a string') | |
if not w: | |
return w, False | |
s = [] | |
c = [c for c in w] | |
for i in range(len(c)): | |
if c[i] in s: | |
return (w, False) | |
elif c[i] not in s: | |
s.append(c[i]) | |
return w, True | |
#using sets | |
#148 | |
def is_isogram(w): | |
if type(w) != str: | |
raise TypeError('Argument should be a string') | |
s = set(c for c in w) | |
if not w or len(w) != len(s): | |
return w, False | |
else: | |
return w, True |
In c#, using Dictionary ... 217 chars
Tuple<string, bool> isIsogram(string word) {
return new Tuple<string, bool>(word, word.ToCharArray().Aggregate(new Dictionary<char, bool>(), (a, b) => {
if (!a.ContainsKey(b)) a.Add(b, true);
return a;
}).Count() == word.Length);
}
Using Set with JS:
function isIsogram (str) {
const cut = str.replace('-', '')
return new Set(cut).size === cut.length
}
Or either using bit mask with JS:
function isIsogram (str) {
let bs = 0b0
for (let i = 0; i < str.length; i += 1) {
const idx = str.charCodeAt(i) - 97
if ((bs & (1 << idx)) === 0) {
bs |= 1 << idx
}
else {
return false
}
}
return true
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using Array in JavaScript:
162 chars
Using object/dict in JavaScript:
161 chars
Using Set in JavaScript:
156 chars