Python中两个字符串相似性的比较

2024-05-08 20:56:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要以下的:

Input: ("a#c","abc")
Output: True

Input:("a#c","abd")
Desired Output: False
Real Output: True

因此,如果这两个字符串的长度相同,并且它们只相差字符#,这表示一个随机字符,那么函数将返回True。 如果没有,我希望它返回False。在

我应该在这个函数中改变什么?在

^{pr2}$

Tags: 函数字符串falsetrueinputoutput字符real
3条回答

现在你只需要测试长度和第一个字符是否匹配。在

for i, c in zip(problem, solution):
    if i != c:
        # that's the first set of chars, but we're already returning??
        return False

    if i == c or "#" == c:
        # wildcard works here, but already would have failed earlier,
        # and still an early return if it IS true!
        return True

相反,您需要遍历整个字符串并返回结果,或者使用all来完成。在

^{pr2}$

或者在一行中:

return len(problem) == len(solution) and \
       all(p_ch==s_ch or p_ch=="#" for p_ch, s_ch in zip(problem, solution)

或者,如果你真的很疯狂(读:你太喜欢正则表达式了),你可以做一些类似的事情:

def checkSolution(problem, solution):
    return re.match("^" + ".".join(map(re.escape, problem.split("#"))) + "$",
                    solution)

您只检查第一个字符。如果第一个字符相同或是True,则不应返回True,但应继续查找第一个不匹配项并仅在for循环外返回True。在

第二个问题是,在您的测试用例中,c永远不是{},因为i是{}的字符,而{}是{}的字符。在

def checkSolution(problem, solution):
    if len(problem) != len(solution): 
        return False
    for i, c in zip(problem, solution):
        if i != '#' and c != '#' and i != c :
            return False
    return True

正如评论中指出的,你的缩进是错误的,应该修正。在

if len(problem) == len(solution):
    # in the line below, 
    # 'i' will contain the next char from problem
    # 'c' will contain the next char from solution
    for i, c in zip(problem, solution):
        # in this line, if they're not equal, you return False
        # before you have a chance to look for the wildcard character
        if i != c:
            return False
        # ...and here you'd fail anyway, because you're testing 
        # the character from the solution string against the wildcard...
        if i == c or "#" == c:
            return True
# ...while in your test, you pass the wildcard in as part of the problem string.
print (checkSolution("a#c","abc"))

相关问题 更多 >