I have a text file containing 5700 words, What i have is a starting word and an ending word, I need to reach end word by replacing one alphabet at a time in the starting word. For example,
I have: HEAD --> TAIL. Result will be: HEAD -> HEAL -> TEAL -> TALL -> TAIL.
I have tried multiple approaches, one was related to graph and other one was where i was storing neighbors of each word in a default dict. What i need to implement is a brute force approach that will replace each alphabet in the word and check if the temp word (word formed by replacing an alphabet) exists in the word list or not. Here's i have tried:
beginWord = "flour"
endWord = "bread"
WordList = []
with open("wordlist.txt", "r") as w: #reading all the words from the file and stoing in the list
for l in w:
WordList.extend(l.split())
WordList.sort()
#print(WordList)
letters = 'abcdefghijklmnopqrstuvwxyz'
temp_word = beginWord
str1 = ''
def test(beginWord, temp_word, letters, str1):
for j in range(len(beginWord)):
str1 = ''
l_list = list(temp_word)
for i in letters:
l_list[j] = i
str1 = ''.join(l_list)
if str1 in WordList and str1 != beginWord:
print(str1)
WordList.remove(str1)
temp_word = str1
str1 = temp_word
j=0
return str1
WordList.remove(beginWord)
while temp_word != endWord:
temp_word= test(temp_word, temp_word, letters, str1)
Now this words for when start word is "flour" and end word is "bread" Here's the output i get:
floor
flood
blood
brood
broad
bread
Now, when i try for other words, for say: witch --> fairy or black --> white, i am unable to reach the end word, although it keeps on replacing alphabet but it fails to reach the end word. Any suggestions?
witch
tofairy
for example? – Andrej Kesely Dec 2 at 19:18