Search code examples
pythonpython-3.xstringpython-itertools

Generate all strings of length n from given letters


Given letters a,b and n=3 I want to get the following strings : aaa,aab,aba,abb,bbb,bba,bab,baa.

That is, I need to generate all strings of length n from the given letters 'a' and 'b'

Thanks in advance !


Solution

  • The call works in theory, but the number of possible strings grows exponentially with n. For a pool of 3 letters and strings of length 20, that would make 3**20 = 3,486,784,401 ~ 3,5bn. You can make a lazy generator though:

    all_ = map(''.join, product('RPS', repeat=20))
    
    >>> next(all_)
    'RRRRRRRRRRRRRRRRRRRR'
    >>> next(all_)
    'RRRRRRRRRRRRRRRRRRRP'
    >>> next(all_)
    'RRRRRRRRRRRRRRRRRRRS'
    >>> next(all_)
    'RRRRRRRRRRRRRRRRRRPR'
    >>> next(all_)
    'RRRRRRRRRRRRRRRRRRPP'