Search code examples
pythonlistwordsalphabet

Generate list of 7 letter words meeting specific conditions - Python


I am trying to generate a list of 7 letter words in python that satisfy the following conditions:

  1. Words are fixed length (7 letters)
  2. Words are only uppercase (I'm using ascii_uppercase)
  3. Is of the form ?D?R?T? where the ? acts as placeholders for letters.

Hence the following are valid examples:

  • ADPRETE
  • BDFRUTW
  • JDQRQTA
  • ZDZRZTZ
  • QDQRQTQ

I'm using the following piece of code, but wondering how to generate words meeting the 3rd criteria. Any help/pointers would be awesome!

from string
from itertools import product

for n in range (7,8):
   for arr in product(string.ascii_uppercase, repeat=n):
      print ''.join(arr)

Solution

  • Generic solution. Just create a mask, and it will do the rest for you :)

    from string import ascii_uppercase
    from itertools import product
    
    def gen_words(mask):
        replace = mask.count('?')
        mask = mask.replace('?', '{}')
        for letters in product(ascii_uppercase, repeat=replace):
            yield mask.format(*letters)
    

    Example:

    >>> list(gen_words('?Z'))
    ['AZ', 'BZ', 'CZ', 'DZ', 'EZ', 'FZ', 'GZ', 'HZ', 'IZ', 'JZ', 'KZ', 'LZ', 'MZ', 'NZ', 'OZ', 'PZ', 'QZ', 'RZ', 'SZ', 'TZ', 'UZ', 'VZ', 'WZ', 'XZ', 'YZ', 'ZZ']