Chris Chris - 1 month ago 5
Python Question

python - how to create an array of all combinations of n character series out of k given characters

I am trying to find a way to create an array where I would have all the variations made out of a set of characters




given A B C, I want to have all possible n-elements combination

for example




A A A B B
A B C A A
A B C A A
A B C A A
etc.


is there any function which would give me something like this?
I had a look at the
print list(itertools.permutations('ABC',5))
but it seems not to work as the 5 is bigger then the number of given characters.

Answer

I believe what you are looking for is product:

list(product('ABC', repeat=5))

Output:

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