python - 比较Python中两个字符串的相似度

标签 python string

我想要以下内容:

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

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

因此,如果两个字符串具有相同的长度并且它们仅差字符 #(代表随机字符),则函数返回 True。 如果不是,我希望它返回 False。

我应该在此函数中更改什么?

def checkSolution(problem, solution):

    if len(problem) != len(solution): 
        return False

    if len(problem) == len(solution):
        for i, c in zip(problem, solution):
            if i != c:
                return False

            if i == c or "#" == c:
                return True

print (checkSolution("a#c","abc"))

print (checkSolution("a#c","abd"))

最佳答案

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

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 为您完成。

if len(problem) == len(solution):
    for p_ch, s_ch in zip(problem, solution):
        if p_ch == "#":  # wildcard
            continue  # so we skip testing this character
        if p_ch != s_ch:
            return False  # This logic works now that we're skipping testing the "#"
    else:  # if we fall off the bottom here
        return True  # then it must be equal
else:
    return False

或在一行中:

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)

关于python - 比较Python中两个字符串的相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185590/

相关文章:

python - 在 python 中有效计算三阶张量

python - 使用 python ijson 读取包含多个 json 对象的大型 json 文件

C++:字符串结构的相等性

java - 数字解析库

python - 使用修改后的值更新 python 中的数据框

python - 如何获取通过 tk.Button 激活的功能的结果?

string - 美国日期(文本)到欧洲日期(日期)的 Excel 转换

regex - Ruby - 正则表达式允许 URL 中包含任何非 ASCII 中文字符

string - 字符串的不变性和并发性

python - 如何计算两列数据框中的真值和假值?