Find all list permutations of splitting a string in Python

后端 未结 6 2312
迷失自我
迷失自我 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 06:55

    My solution allows you to also set a threshold for the minimum size of sub string

    This is my code:

    def split_string (s, min_str_length = 2, root_string=[], results=[] ):
        """
        :param s: word to split, string
        :param min_str_length: the minimum character for a sub string
        :param root_string:  leave empty
        :param results: leave empty
        :return: nested list of all possible combinations of word split according to the minimum substring length
        """
        for i in range(min_str_length,len(s)):
            if i == min_str_length:
                primary_root_string=root_string
            else:
                root_string = primary_root_string
            if len(s[i:])>= min_str_length :
                results.append(list(chain(*[root_string,[s[:i]],[s[i:]]])))
                root_string = list(chain(*[root_string,[s[:i]]]))
                split_string(s[i:], min_str_length, root_string, results)
        return results
    

    Examples of use:

    Input: split_string ('monkey', min_str_length = 1, root_string=[], results=[] )
    Output: 
    [['m', 'onkey'],
     ['m', 'o', 'nkey'],
     ['m', 'o', 'n', 'key'],
     ['m', 'o', 'n', 'k', 'ey'],
     ['m', 'o', 'n', 'k', 'e', 'y'],
     ['m', 'o', 'n', 'ke', 'y'],
     ['m', 'o', 'nk', 'ey'],
     ['m', 'o', 'nk', 'e', 'y'],
     ['m', 'o', 'nke', 'y'],
     ['m', 'on', 'key'],
     ['m', 'on', 'k', 'ey'],
     ['m', 'on', 'k', 'e', 'y'],
     ['m', 'on', 'ke', 'y'],
     ['m', 'onk', 'ey'],
     ['m', 'onk', 'e', 'y'],
     ['m', 'onke', 'y'],
     ['mo', 'nkey'],
     ['mo', 'n', 'key'],
     ['mo', 'n', 'k', 'ey'],
     ['mo', 'n', 'k', 'e', 'y'],
     ['mo', 'n', 'ke', 'y'],
     ['mo', 'nk', 'ey'],
     ['mo', 'nk', 'e', 'y'],
     ['mo', 'nke', 'y'],
     ['mon', 'key'],
     ['mon', 'k', 'ey'],
     ['mon', 'k', 'e', 'y'],
     ['mon', 'ke', 'y'],
     ['monk', 'ey'],
     ['monk', 'e', 'y'],
     ['monke', 'y']]
    

    or

    Input: split_string ('monkey', min_str_length = 2, root_string=[], results=[] )
    Output: [['mo', 'nkey'], ['mo', 'nk', 'ey'], ['mon', 'key'], ['monk', 'ey']]
    
    

提交回复
热议问题