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\'
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']