Find all list permutations of splitting a string in Python

后端 未结 6 2300
迷失自我
迷失自我 2020-12-30 06:42

I have a string of letters that I\'d like to split into all possible combinations (the order of letters must be remain fixed), so that:

s = \'monkey\'
         


        
6条回答
  •  执笔经年
    2020-12-30 07:08

    def splitter(str):
        for i in range(1, len(str)):
            start = str[0:i]
            end = str[i:]
            yield (start, end)
            for split in splitter(end):
                result = [start]
                result.extend(split)
                yield result
    
    combinations = list(splitter(str))
    

    Note that I defaulted to a generator to save you from running out of memory with long strings.

提交回复
热议问题