【发布时间】:2019-02-09 05:43:13
【问题描述】:
我正在设计一个猜字游戏,我需要一些关于其中一个功能的帮助。
该函数接收 2 个输入并返回 true 或 false。
输入 my_word 包含猜测并与某个单词匹配的字母。
输入 other_word 是一些要与 my_input 进行比较的词。
例子:
>>> 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
我的问题是应用它来返回 False,就像上一个示例一样,我不知道该怎么做。这是我到目前为止所做的。它有效,但不适用于 my_word 中的一个猜测字母在 other_word 中出现 2 次的情况。在这种情况下,我返回 true,但它应该是 False。 输入必须与示例中的格式完全相同(下划线后的空格)。
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))
【问题讨论】:
-
Python 3. 谢谢
-
仅供参考:您可以轻松地进行链式替换,而不是使用 for 循环。
sw = my_word.replace(' ').replace('_')
标签: python python-3.x string list filtering