Alagappan Ramu
Alagappan Ramu

Reputation: 2358

Generating combinations of two strings using Python

I have a string str1 = "ABC" and I need to insert 0 to len(str1) number of "x"s in the string str1 except at the last position.

So in the above example, I want a resultant list with 0 to 2 "x"s placed before or inside the string which looks like

["ABC",
 "xABC",
 "AxBC",
 "ABxC",
 "xxABC",
 "xAxBC",
 "xABxC",
 "AxxBC",
 "AxBxC",
 "ABxxC"]

I tried some code which is as follows (I do realize that I have missed out few combinations in this):

>>> for i in range(1, len(str1)):
...     for k in range(len(str1)):
...         str1[:k]+"x"*i+str1[k:]
... 
'xABC'
'AxBC'
'ABxC'
'xxABC'
'AxxBC'
'ABxxC'
>>> 

I am not really sure about how to approach the other case with inter-leavings between the two for e.g. xAxBC etc

What is the best approach to solve this?

Upvotes: 1

Views: 1440

Answers (1)

falsetru
falsetru

Reputation: 368894

Using itertools.combinations_with_replacement to get indexes to insert xs.:

import itertools

str1 = "ABC"
lst = list(str1)
for n in range(len(str1)):
    for idxs in itertools.combinations_with_replacement(range(len(str1)), n):
        xs = lst[:]
        for i in reversed(idxs): # Use reversed, otherwise index become invald
            xs.insert(i, 'x')
        print(''.join(xs))

output:

ABC
xABC
AxBC
ABxC
xxABC
xAxBC
xABxC
AxxBC
AxBxC
ABxxC

Upvotes: 4

Related Questions