python - 字符串比较和排序功能

标签 python python-3.x string list filtering

我正在设计一个猜词游戏,我需要一些关于其中一个功能的帮助。 该函数接收 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 中出现两次的情况。在本例中,我返回 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))

最佳答案

您可以创建字符串的“无空格”版本和“无空格、无下划线”版本,然后比较每个字符以查看非下划线字符是否匹配,或者与下划线对应的字符是否已被使用。例如:

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

关于python - 字符串比较和排序功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54599026/

相关文章:

python - 如何在django中从外部应用程序添加与模型的多对一关系

python - 在 Selenium 期间更改代理服务器

python - 是否可以在Linux上构建OpenCV应用并在Windows上执行它?

Python (tkinter) 错误 : "CRC check failed"

python-3.x - Elasticsearch 7:无法解析日期

python - 在Python中读取具有最新时间戳的文本文件

将存储在 char 数组中的字符串部分复制到另一个数组

Python 语法/列表切片问题 : What does this syntax mean?

java - 将 infix 转换为 Postfix 时扫描多位数字

python - 正则表达式搜索程序,如何在迭代文本时不重复答案? (Python3)