Question

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)
Was it helpful?

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']

OTHER TIPS

import string
import itertools as IT

for arr in IT.product(string.ascii_uppercase, repeat=4):
    print ''.join('{}D{}R{}T{}'.format(*arr))
from string import ascii_uppercase
from itertools import product

for letters in product(ascii_uppercase, repeat=4):
    print "%sD%sR%sT%s" % letters
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top