Search code examples
pythonauto-generate

Generating words upto and including 20 letters


alphabet =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
key = ''
for a in range(26):
    key += alphabet[a]
    print(key)
    key = ''

for a in range(26):
    for b in range(26):
        key += alphabet[a]+ alphabet[b]
        print(key)
        key = ''

for a in range(26):
    for b in range(26):
        for c in range(26):
            key += alphabet[a]+ alphabet[b]+ alphabet[c]
            print(key)
            key = ''

Hey! I'm in need of an efficient program to generate every word of 20 or less letters. I have created the code above to generate all possible 1, 2 and 3 letter words. However, this seems to be an inefficient method. So my question is: 'Is There a more efficient method to generate these words upto and including 20 letters' Edit: I'm in python 2.7.9 if that helps


Solution

  • The below uses itertools.product to produce the combinations of letter and ''.join to join them into a word.

    from string import ascii_lowercase as lowercase
    from itertools import product
    
    length = 5
    
    for word in (''.join(x) for x in product(lowercase, repeat=length)):
        print(word)
    

    Pretty much no matter what you do this is going to take a long time. Even a 5 letter word will have 26**5 possibilities, which works out to 11881376 or almost 12 million. Unless generating all the 20 letter combinations is an absolute requirement, you should look for a way to avoid it.