Python递归通过滑动窗口拆分字符串

问题描述 投票:-2回答:1

最近,我面临一个有趣的编码任务,涉及以给定的K限制大小分割一个字符串多个排列。

例如:

s = "iamfoobar"
k = 4  # the max number of the items on a list after the split

s可以分为以下组合

[
    ["i", "a", "m", "foobar"],
    ["ia", "m", "f", "oobar"],
    ["iam", "f", "o", "obar"]
# etc
]

我试图弄清楚如何使用快速递归功能来做到这一点,但我无法使其正常工作。

我已经尝试过,但是似乎没有用

def sliding(s, k):
    if len(s) < k:
        return []
    else:
        for i in range(0, k):
            return [s[i:i+1]] + sliding(s[i+1:len(s) - i], k)

print(sliding("iamfoobar", 4))

只有这个

['i', 'a', 'm', 'f', 'o', 'o']
python python-3.x
1个回答
0
投票

实现中的主要问题是您的循环没有执行应做的事情,因为它返回第一个结果而不是附加结果。

这是一个实现示例:

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))
© www.soinside.com 2019 - 2024. All rights reserved.