Skip to content Skip to sidebar Skip to footer

Find All Possible Combinations Of Two Characters Of An N Length

I have two characters, for example: a = 'a' b = 'b' And I need to find all possible combinations of those two characters that will make a string of length N. For example, if N = 3

Solution 1:

itertools.product is what you want here:

>>> from itertools import product
>>> a = 'a'>>> b = 'b'>>> N = 3>>> lst = [a, b]
>>> [''.join(x) for x in product(lst, repeat = N)]
['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']

Which can also be written with a triple nested list comprehension:

>>> [x + y + z forxin lst foryin lst forzin lst]
['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']

Post a Comment for "Find All Possible Combinations Of Two Characters Of An N Length"