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)
).