2 回答

TA貢獻1876條經驗 獲得超6個贊
您的第一個主要問題是,盡管您使用循環,但您會立即返回一個列表。因此,無論您如何修復周圍的一切,您的輸出都永遠不會符合您的預期……一個列表。
其次,在您開始的遞歸調用中,s[i:i+1]但根據您的示例,您需要所有前綴,因此s[:i]更合適。
另外,在遞歸調用中你永遠不會減少k這是自然的遞歸步驟。
最后,你的停止條件似乎也是錯誤的。如上所述,如果自然步驟減少,k則自然停止。這是因為將字符串拆分為 1 個部分的唯一方法是字符串本身......if k == 1return [[s]]
重要的是要牢記您的最終輸出格式,并思考它如何在您的步驟中發揮作用。在這種情況下,您希望以列表的形式返回所有可能排列的列表。因此,在 的情況下k == 1,您只需返回單個字符串列表的列表。
現在,作為這一步,您希望每次都采用不同的前綴,并向其添加調用字符串其余部分的所有排列k-1??偠灾?,代碼可以是這樣的:
def splt(s, k):
if k == 1: # base sace - stop condition
return [[s]]
res = []
# loop over all prefixes
for i in range(1, len(s)-k+2):
for tmp in splt(s[i:], k-1):
# add to prefix all permutations of k-1 parts of the rest of s
res.append([s[:i]] + tmp)
return res
您可以在一些輸入上對其進行測試,看看它是如何工作的。
如果您不限于遞歸,另一種方法是使用itertools.combinations. 您可以使用它在字符串中創建所有索引組合,將其拆分為多個k部分,然后簡單地連接這些部分并將它們放入列表中。原始版本類似于:
from itertools import combinations
def splt(s, k):
res = []
for indexes in combinations(range(1, len(s)), k-1):
indexes = [0] + list(indexes) + [len(s)] # add the edges to k-1 indexes to create k parts
res.append([s[start:end] for start, end in zip(indexes[:-1], indexes[1:])]) # concatenate the k parts
return res

TA貢獻1757條經驗 獲得超7個贊
您實現中的主要問題是您的循環沒有執行預期的操作,因為它返回第一個結果而不是附加結果。
下面是一個實現示例:
def sliding(s, k):
# If there is not enough values of k is below 0
# there is no combination possible
if len(s) < k or k < 1:
return []
# If k is one, we return a list containing all the combinations,
# which is a single list containing the string
if k == 1:
return [[s]]
results = []
# Iterate through all the possible values for the first value
for i in range(1, len(s) - k + 2):
first_value = s[:i]
# Append the result of the sub call to the first values
for sub_result in sliding(s[i:], k - 1):
results.append([first_value] + sub_result)
return results
print(sliding("iamfoobar", 4))
添加回答
舉報