我希望得到以下内容:
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"))
答案 0 :(得分:2)
您只检查第一个字符。如果第一个字符相同或者是True
,则不应返回#
,但是您应该继续查找第一个不匹配并仅在for循环之外返回True
。 / p>
第二个问题是,在您的测试用例中,变量c
永远不会是'#'
,因为i
是problem
的字符,而c
是solution
。
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
答案 1 :(得分:2)
现在你只测试长度和第一个字符匹配。
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)
答案 2 :(得分:0)
正如评论中所指出的那样,你的缩进是愚蠢的,应该修复。
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"))
答案 3 :(得分:0)
您的函数的一行版本:
def check_solution(problem, solution):
return (len(problem) == len(solution) and
all(ch==solution[i] for i, ch in enumerate(problem) if ch != '#'))
测试:
>>> check_solution("a#c", "abc")
True
>>> check_solution("a#c", "abd")
False