Mario Arango
Mario Arango

Reputation: 11

Find all combinations of three letters in a list of nine positions

i have a list like:

['A','B','C']

what i want to obtain is all the combinations of these three letters in a nine length list, it can be with repeated letters.

for example:

combination_1 = ['A','A','A','A','A','A','A','A','A']
combination_2 = ['A','A','A','A','C','A','A','A','A']
combination_3 = ['B','B','B','A','C','A','A','C','C']

I would like to do it in python but if there is a solution in other language it will work too.

Upvotes: 0

Views: 76

Answers (1)

user15750474
user15750474

Reputation:

Combinations with replacement can give it:

from itertools import combinations_with_replacement

list_ = ["A", "B", "C"]
for comb in combinations_with_replacement(list_, 9):
    print(comb)

Prints

('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B')
('A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'B', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'A', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B')
('A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C')
('A', 'A', 'A', 'A', 'A', 'B', 'B', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'B', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'A', 'C', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B')
('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C')
('A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C')
('A', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'B', 'C', 'C', 'C', 'C')
('A', 'A', 'A', 'A', 'C', 'C', 'C', 'C', 'C')
('A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B')
('A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'C')
....

and more :) (55 in total).

If you want list outputs, you can print(list(comb)) in the loop above.

(after the comment's correction)

itertools.product with repeat argument can give it:

from itertools import product

list_ = ["A", "B", "C"]
for comb in product(list_, repeat=9):
    print(comb)

3**9 = 19683 items it produces.

Upvotes: 6

Related Questions