Question

I'm trying to make a list of words from given characters (word) with given length. Each word is a combination of the given characters(word) and [a..z][0..9] (no uppercase)

E.g: Length = 5, given words: out (given word's length < max length)

The function should return a list that contain: outaa, outba, ..., out9a, out0a, ..., outab, outbb, ..., out9b, out0b, ..., aouta, bouta, ...aaout, baout ...

Meant that we fill the remaining character with [a..z][0..9] with the position of the given word being shifted one at a time.

I'm still thinking about a way to do that but couldn't come up with any ideas yet. Anyone mind giving me a help, please?

Thank you so much

Was it helpful?

Solution

Use itertools.product() to produce the remaining characters, then cycle the word position with collections.deque to produce all permutations:

from collections import deque
from itertools import product
from string import ascii_lowercase, digits

def generate_words(start, length, _chars=ascii_lowercase + digits):
    remainder = length - len(start)
    if remainder < 1:
        yield start
        return
    for letters in product(_chars, repeat=remainder):
        combo = deque(letters + (start,))
        for _ in range(remainder + 1):
            yield ''.join(combo)
            combo.rotate()

This is a generator, loop over the output:

>>> for word in generate_words('out', 5):
...     print word
... 
aaout
outaa
aouta
about
outab
bouta
acout
outac
couta
adout
outad
douta
aeout
outae
eouta
afout
outaf
# etc.

or call list() on the generator and be prepared to store a large number of words if the difference between len(start) and length starts to go beyond 3 (an additional 4 characters produces 8398080 combinations, 5 characters is 362797056 combinations; the formula is (36**remainder)*(remainder + 1)).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top