首页 > 解决方案 > Python中将字符串拆分为n个子字符串的排列

问题描述

我有每个字母的字符串,我想将其拆分为所有可能的组合,但具有给定数量的子字符串,因此:

a = 'abcdefghi...'

分成4个子串:

comb = [['abcdefghi...'], [''], [''], ['']],[['bcdefghi...'], ['a'], [''], ['']],[['cdefghi...'], ['ab'], [''], ['']]....[[''], [''], [''], ['abcdefghi...']]

我最大的问题 rn 是对整个字母表执行此操作的时间消耗。

有任何想法吗?

标签: pythonruntimepermutation

解决方案


def per_string(s,n, out_list=[], lst=[]):
    if s == "":
        out_list.append(lst[::-1])
    for i in range(len(s)):
        if len(lst)<n:
            lst.append([s[i:]])
            per_string(s[:i], n,out_list, lst)
            lst.pop()
    return out_list

推荐阅读