1

I met a problem, I need to create a list of all possible variations of string. I had already tried some methods from itertools, like [''.join(i) for i in itertools.permutations('abc')] or

(comb = [''.join(i) for i in itertools.combinations_with_replacement('abc',3)] but they have a bit different result, as i was expected. I need ALL variations, so permutation isn't the way to do it. Combinations with replacement were quite good, but there were missing some subsequence The result of this operation is:

aab
aac
abb
abc
acc
bbb
bbc
bcc
ccc

But i need output 'aba', 'acb' 'bab',etc as well (Need to cover all possible variants) Maybe im missing another method in itertools, that would help me? Thanks for any help and advice

1
  • 1
    Have you tried getting all permutations of each with-replacement combination? Commented Nov 27, 2020 at 14:58

1 Answer 1

3

You use itertools.product with as many iterables as the size of your string:

from itertools import product

s = 'abc'
ss = [s] * len(s)
for r in product(*ss):
    print(''.join(r))

aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc
Sign up to request clarification or add additional context in comments.

1 Comment

product allows you the even simpler: for r in product(s, repeat=len(s)):

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.