I'm designing a guess word game and I need some help with one of the functions. The function receives 2 inputs and returns true or false.
The input my_word contains letters that were guessed and match to a certain word. The input other_word is some word to compare with my_input. examples:
>>> match_with_gaps("te_ t", "tact")
False
>>> match_with_gaps("a_ _ le", "apple")
True
>>> match_with_gaps("_ pple", "apple")
True
>>> match_with_gaps("a_ ple", "apple")
False
My problem is applying it to return a False as in the last example and I'm not sure how to do it. This is what I have done so far. It works but not for a case when a one guessed letter in my_word appears 2 time in other_word. In this case I'm returning true but it should be False. The inputs must be the exactly in the format as in the example (space after underscore).
def match_with_gaps(my_word, other_word):
myWord = []
otherWord = []
myWord_noUnderLine = []
for x in my_word:
if x != " ": # remove spaces
myWord.append(x)
for x in myWord:
if x != "_": # remove underscore
myWord_noUnderLine.append(x)
for y in other_word:
otherWord.append(y)
match = ( [i for i, j in zip(myWord, otherWord) if i == j] ) # zip together letter by letter to a set
if len(match) == len(myWord_noUnderLine): # compare length with word with no underscore
return True
else:
return False
my_word = "a_ ple"
other_word = "apple"
print(match_with_gaps(my_word, other_word))
You could create a "no space" version and a "no space, no underscore" version of your string and then compare each character to see if non underscore characters matched or if characters corresponding to an underscore have already been used. For example:
def match_with_gaps(match, guess):
nospace = match.replace(' ', '')
used = nospace.replace('_', '')
for a, b in zip(nospace, guess):
if (a != '_' and a != b) or (a == '_' and b in used):
return False
return True
print(match_with_gaps("te_ t", "tact"))
# False
print(match_with_gaps("a_ _ le", "apple"))
# True
print(match_with_gaps("_ pple", "apple"))
# True
print(match_with_gaps("a_ ple", "apple"))
# False
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments