All possible ways to interleave two strings

前端 未结 5 612
傲寒
傲寒 2021-01-03 22:30

I am trying to generate all possible ways to interleave any two arbitrary strings in Python.

For example: If the two strings are \'ab\' and \'cd\'

5条回答
  •  一生所求
    2021-01-03 23:14

    You only need to compare the index of a to b and c to d then filter out those elements where index of a is greater than index of b and index of c is greater than index of d.

    def interleave(s, t):
        mystring = s + t
        return [el for el in [''.join(item) for item in permutations(mystring) if  item.index('a') < item.index('b') and item.index('c') < item.index('d')]]
    

    Demo:

    >>> from itertools import permutations
    >>> s = 'ab'
    >>> t = 'cd'
    >>> [el for  el in [''.join(item) for item in permutations(s+t) if item.index('a') < item.index('b') and item.index('c') < item.index('d')]]
    ['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab']
    

提交回复
热议问题