1

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?

2

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

wow, you are too fast, it took me this long just to find what it's called. Here's the reference: en.wikipedia.org/wiki/…
Thanks for the amazing answer! While this seems to work fine to strings of length upto 10-15, it becomes excruciatingly slow for larger numbers. Is there anything that can be done to speed it up? Like memoization for example? I was trying something on the lines that (xABC, AxBC, ABxC) are repeated again when x is added at the beginning like xxABC, xAxBC, xABxC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.