简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM