user3514461 user3514461 - 2 months ago 14
Python Question

How to make all possible combinations of a word in Python

I have a txt file with all of the letters in the alphabet that looks like this:

a

b

c

etc..

I also have a word list of words that is only 3 letters long:

ago

age

bat

bag

etc...

I want to create a list that prints out all of the combinations possible starting with the first word ago:

My test program looks like this:

allcombi=[]
s= list("ago")
the.list=[]
with open("alfabeth.txt", "r", encoding = "utf-8") as letters:
for line in letters:
letter = line.strip()
s[0]=letter
print(s)


Now I only change the first letter, but I have a really hard time trying to join the letters because it only looks like this:

['a', 'g', 'o']
['b', 'g', 'o']
....

HELP WITH:


  1. Print it out as ['ago','bgo'] instead

  2. Instead of just changing the first letter, change it one letter at a time in index 0,1 and 2 one letter at a time in the word. The output should be 27*3 rows long with ['ago','bgo',........,'agx',agy,'agz']



I will later search for all of the items in my new list in a dictionary but that I can figure out myself it's just this part that really gotten me stuck.

Answer

This will generate a list of all combinations for a given word:

letters = 'abcdefghijklmnopqrstuvwxyz'
word = "ago"
combos = []
for i in xrange(len(word)):
    for l in letters:
        combos.append( word[:i]+l+word[i+1:] )