This function will check a word with some letters missing, missing letters will be indicated by an "_ " (notice that there is a space after the underscore). The word with missing letters needs to be checked against a full word and if both words are found to be identical ( disregarding the "_ " the function should return True otherwise False.
This is part of a problem set from the MIT Online Course. here is how i managed to do this:
def match_with_gaps(my_word, other_word):
'''
my_word: string with "_" characters
other_word: string, regular English word
returns: boolean, True if all the actual letters of my_word match the
corresponding letters of other_word, or the letter is the special symbol "_",
and my_word and other_word are of the same length;
False otherwise:
'''
my_word = my_word.replace(' ','')
for char in my_word:
if char.isalpha():
if my_word.count(char) != other_word.count(char):
return False
return len(my_word) == len(other_word)
An example :
a = match_with_gaps('a p p _ e', 'apple')
b = match_with_gaps('a p p _ c', 'apple')
print(a) >> outputs : True
print(b) >> outputs : False
I also came up with another way:
def match_with_gaps(my_word, other_word):
'''
my_word: string with _ characters, current guess of secret word
other_word: string, regular English word
returns: boolean, True if all the actual letters of my_word match the
corresponding letters of other_word, or the letter is the special symbol
_ , and my_word and other_word are of the same length;
False otherwise:
'''
my_word = my_word.replace(' ', '')
if len(my_word) != len(other_word):
return False
else:
for i in range(len(my_word)):
if my_word[i] != '_' and (
my_word[i] != other_word[i] \
or my_word.count(my_word[i]) != other_word.count(my_word[i]) \
):
return False
return True
which will give the same output but using a different method.
Which way is more efficient / will give more accurate results? and is there a third better method? Please give reason to your answer. And thanks in advance.
match_with_gaps('_ _ _ _e', 'apple')
? \$\endgroup\$