+ 2
Please help me with a better way of implementing this code. If doesn't pass some test like... Empty string test
def isogram (word): if type (word) != str: raise TypeError ("argument is not a string") elif len(list(word)) == 0: return (word, False) else : word = word .lower() for char in word: if word.count(char) > 1: return (word , False ) else : return (word,True) print (isogram ("design")
3 ответов
+ 8
def isogram (word):
if type (word) != str:
raise TypeError ("argument is not a string")
elif len(list(word)) == 0:
return (word, False)
else :
word = word .lower()
for char in word:
if word.count(char) > 1:
return (word , False )
# don't return True before end of loop (while all chars tested)
#else :
#return (word,True)
# implicite: if not already False returned, return True (all chars are unique)
return (word,True)
print (isogram ("design")) # don't forgot to close all parenthesis (rounded brackets)
# another way of implementing isogram test, is to use set properties (uniques items list), and test if length of set is equal to length of list (so it proove that each char is unique):
def isogram_bis(word):
if type (word) != str:
raise TypeError ("argument is not a string")
# implicite else:
count_char = len(word) # not necessary to transform string to list
if count_char != 0 and count_char == len(set(word)):
return (word,True)
# implicite else:
return (word,False)
print (isogram_bis("design"))
+ 1
No... Just to define a function that checks if a word is an isogram
0
Thanks a lot...