[英]Comparing similarity of two strings in Python
我想要以下內容:
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"))
您只檢查第一個字符。 你不應該回到True
的情況下,第一個字符是相同的或者是#
,但你應該去找到第一個不匹配,返回True
只能在外面的for循環。
第二個問題是,在您的測試用例中,變量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
現在,您只測試長度和第一個字符是否匹配。
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)
正如評論中指出的那樣,您的縮進已弄糟,應予以修復。
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"))
功能的一行版本:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.