Return all possible combinations of a string when splitted into n strings

前端 未结 3 750
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 07:10

I made a search for stackoverflow about this but couldn\'t find a way to do it. It probably involves itertools.

I want to find all the possible results of splitting

3条回答
  •  长发绾君心
    2021-01-03 07:29

    Including empty strings in your results will be rather awkward with itertools.combinations(). It's probably easiest to write your own recursive version:

    def partitions(s, k):
        if not k:
            yield [s]
            return
        for i in range(len(s) + 1):
            for tail in partitions(s[i:], k - 1):
                yield [s[:i]] + tail
    

    This will work for any number k of desired partitions for any string s.

提交回复
热议问题