为了账号安全,请及时绑定邮箱和手机立即绑定

字符串比较排序功能

字符串比较排序功能

qq_笑_17 2021-11-02 20:00:19
我正在设计一个猜字游戏,我需要一些关于其中一个功能的帮助。该函数接收 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 Falsemy_word = "a_ ple"other_word = "apple"print(match_with_gaps(my_word, other_word))
查看完整描述

2 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

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


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


查看完整回答
反对 回复 2021-11-02
?
撒科打诨

TA贡献1934条经验 获得超2个赞

这条线在这里:

 if len(match) == len(myWord_noUnderLine)

不会给你你现在想要的。在“a_ple”示例中,空格和“_”都被删除,因此您的 myWord_noUnderLine 变量将为“aple”,因此检查“aple”和“apple”之间的长度匹配肯定会失败


查看完整回答
反对 回复 2021-11-02
  • 2 回答
  • 0 关注
  • 141 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号