Search code examples
pythonpython-3.xstringlistpython-itertools

Print all possible combination of words of length 10 from a list letters with repeating 'A' exactly twice


I have a list of 5 letters ['A', 'B', 'N', 'M','E'].

I want to print all the words (word means a sequence of letters, it doesn't have to be a valid English word) of length 10 letters that have exactly two letters A. Order is important.

I have tried with itertools.product as it appeared to be the most promising solution:

from itertools import product

letters = ['A', 'B', 'N', 'M','E']

for word in product(letters, repeat=10):
    res = ''.join(str(x) for x in word)
    print(res)

The problem with this approach is that I can't really control the number of occurrences of the letter A as it returns the word composed of 10 letters of A.

Is there a solution for this? Thanks

EDIT 1 Example of possible words: BANAMEMNEB : it has only twice the letter A, we don't care about other letters.


Solution

  • The way to do it efficiently is to iterate over all combinations of the positions of the letters 'A', and for each such combination - iterate over all the ways other letters can be positioned, and just insert the 'A's there.

    Be warned that with your inputs this will produce almost 3 million words!

    On my machine it was printing the words for so long that I had to manually stop execution.

    So here is the smaller example:

    letters = ['A', 'b', 'c']
    num_As = 2
    num_total = 4
    
    from itertools import combinations, product
    for indices_A in combinations(range(num_total), num_As):
        for rest in product(letters[1:], repeat=num_total - num_As):
            rest = list(rest)
            for index_A in indices_A:
                rest.insert(index_A, 'A')
            print(''.join(rest))
    
    AAbb
    AAbc
    AAcb
    AAcc
    AbAb
    AbAc
    AcAb
    AcAc
    AbbA
    AbcA
    AcbA
    AccA
    bAAb
    bAAc
    cAAb
    cAAc
    bAbA
    bAcA
    cAbA
    cAcA
    bbAA
    bcAA
    cbAA
    ccAA