gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:03 27 4
gpt4 key购买 nike

我想要以下内容:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com