我想檢查 s3 是否是 s1 和 s2 的有組織的組合。所以我寫了這個:
def organized_comp(s1,s2,s3):
l1, l2, l3 = len(s1), len(s2),len(s3)
if (l1 == 0 and l2 == 0 and l3 ==0):
return True
if (l1 == 0 and s2 == s3) or (l2 == 0 and s1 == s3):
return True
if (l3 != (l1 l2)) or (l3 == 0 and (l1 > 0 or l2 > 0)):
return False
if s1 and s1[0] == s3[0]:
return True and organized_comp(s1[1:], s2, s3[1:])
if s2 and s2[0] == s3[0]:
return True and organized_comp(s1, s2[1:], s3[1:])
當我發送: s1 = "ABZ" , s2 = "ABAXZ", s3 = "ABAXABZZ" 它回傳 False 并且它需要回傳 True。我想我知道這個問題 - 因為 s1[0] = s2[0] 并且它總是以 s1 開頭(如果我發送 s2 = "ABZ" , s1 = "ABAXZ" 它可以作業)。
我該如何糾正它?
uj5u.com熱心網友回復:
您對問題的分析是正確的:如果s1[0] == s2[0],那么您不知道應該使用哪個字符。因此,您應該嘗試兩種可能性,如果其中至少一種有效,則回傳 True。
這可以通過邏輯運算子來完成or。
另請注意,您的“如果森林”缺少應該回傳 False: when l1 l2 == l3but 的情況s3[0] not in (s1[0], s2[0])。在 python 中,與幾乎所有其他編程語言不同,如果return函式中缺少 a,python 不會崩潰,并且函式會靜默回傳None,就好像存在顯式的return None. 因此,您撰寫它的方式organized_comp('a', 'b', 'c')將回傳None而不是False.
您的某些條件有點多余,例如以下兩個條件是等效的:
(l3 != (l1 l2)) or (l3 == 0 and (l1 > 0 or l2 > 0))
(l3 != (l1 l2)) # if the second part was True, then the first part would be True anyway
這是一個建議的修復:
def organized_comp(s1,s2,s3):
l1, l2, l3 = len(s1), len(s2),len(s3)
return (l3 == l1 l2) and (
(l3 == 0) or
(l1 > 0 and s3[0] == s1[0] and organized_comp(s1[1:], s2, s3[1:])) or
(l2 > 0 and s3[0] == s2[0] and organized_comp(s1, s2[1:], s3[1:]))
)
uj5u.com熱心網友回復:
在評論中發現,OP 需要一個沒有解決方案 replace
沒有的解決方案replace:
s1 = "ABZ"
s2 = "ABAXZ"
base = "ABAXABZZ"
def is_combination_of(base: str, p1: str, p2: str):
if len(base) > 0:
try:
p1i = p1.index(base[0])
return is_combination_of(base[1:], p1[:p1i] p1[p1i 1:], p2)
except ValueError:
pass
try:
p2i = p2.index(base[0])
return is_combination_of(base[1:], p1, p2[:p2i] p2[p2i 1:])
except ValueError:
pass
if base == p1 == p2 == '':
return True
return False
print(is_combination_of(base, s1, s2))
您的錯誤是假設對于您中的每個第一個字符,s3您都可以找到該字符作為s1or的第一個字符s2。對于這種簡化的情況,此方法失敗:
s1 = 'CA'
s2 = 'CB'
s3 = 'ABCC'
如您所見,您需要查看 的所有字符s1并s2確定是否s3[0]在其中。
對于這種確切的情況,不需要遞回方法,但如果您愿意,可以通過以下方式完成:
s1 = "ABZ"
s2 = "ABAXZ"
base = "ABAXABZZ"
def is_combination_of(base: str, p1: str, p2: str):
if len(base) > 0:
if base[0] in p1:
return is_combination_of(base[1:], p1.replace(base[0], '', 1), p2)
if base[0] in p2:
return is_combination_of(base[1:], p1, p2.replace(base[0], '', 1))
if base == p1 == p2 == '':
return True
return False
print(is_combination_of(base, s1, s2))
但這是一種非常低效的方法。我的意思是,通過遞回。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403061.html
標籤:
上一篇:有沒有辦法允許for回圈和陣列元素的數量在演算法中是可變的?-爪哇
下一篇:需要幫助理解x86程式集中的遞回
