Find all possible combinations of two characters of an N length

后端 未结 1 311
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 16:05

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 s

相关标签:
1条回答
  • 2021-01-29 16:39

    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 for x in lst for y in lst for z in lst]
    ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']
    
    0 讨论(0)
提交回复
热议问题