Find all list permutations of splitting a string in Python

后端 未结 6 2314
迷失自我
迷失自我 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:05

    A string (as opposed to list) oriented approach is to think of the each adjacent pair of characters being separated by either a space or empty string. That can be mapped to 1 and 0, and the number of possible splits are a power of 2:

    2 ^ (len(s)-1)

    for example, "key" can have '' or ' ' separating 'ke' and a '' or ' ' separating 'ey' which leads to 4 possibilities:

    • key ('' between 'k' and 'e', '' between 'e' and 'y')
    • k ey (' ' between 'k' and 'e', '' between 'e' and 'y')
    • k e y (' ' between 'k' and 'e', ' ' between 'e' and 'y')
    • ke y ('' between 'k' and 'e', ' ' between 'e' and 'y')

    An unreadable python one liner that gives you a generator in string form:

    operator_positions = (''.join([str(a >> i & 1).replace('0', '').replace('1', ' ') + s[len(s)-1-i] for i in range(len(s)-1, -1, -1)]) for a in range(pow(2, len(s)-1)))
    

    A readable version of this generator with comments and sample:

    s = 'monkey'
    s_length = len(s)-1  # represents the number of ' ' or '' that can split digits
    
    operator_positions = (
        ''.join(
            [str(a >> i & 1).replace('0', '').replace('1', ' ') + s[s_length-i]
             for i in range(s_length, -1, -1)])   # extra digit is for blank string to always precede first digit
        for a in range(pow(2, s_length))   # binary number loop
    )
    for i in operator_positions:
        print i
    

    str(a >> i & 1) converts a into a binary string, which then has it's 0's and 1's replaced by '' and ' ', respectively. The binary string is an extra digit long so that the first digit is always ''. That way, as the digit splitter is combined with the first character, it always results in just the first character.

提交回复
热议问题