I’m having trouble with a program, the program takes one word, and changing one letter at a time, converts that word into the target word. Although, keep in mind that the converted word must be a legal word according to a dictionary of words that I’ve been given.
I’m having trouble figuring out how to make it recursive. The program has a limit to the amount of steps it must take.
The output needs to be a list. So if the parameters for the function changeling are
changeling(“find”,”lose”), the output should be:
[‘find’,’fine’,’line’,’lone’,’lose’].
with my current code:
def changeling(word,target,steps):
holderlist=[]
i=0
if steps<0 and word!=target:
return None
if steps!=-1:
for items in wordList:
if len(items)==len(word):
i=0
if items!=word:
for length in items:
if i==1:
if items[1]==target[1] and items[0]==word[0] and items[2:]==word[2:]:
if items==target:
print "Target Achieved"
holder.list.append(target)
holderlist.append(items)
holderlist.append(changeling(items,target,steps-1))
elif i>0 and i<len(word)-1 and i!=1:
if items[i]==target[i] and items[0:i]==word[0:i] and items[i+1:]==word[i+1:]:
if items==target:
print "Target Achieved"
holderlist.append(items)
holderlist.append(changeling(items,target,steps-1))
elif i==0:
if items[0]==target[0] and items[1:]==word[1:]:
if items==target:
print "Target Achieved"
holderlist.append(items)
holderlist.append(changeling(items,target,steps-1))
elif i==len(word)-1:
if items[len(word)-1]==target[len(word)-1] and items[0:len(word)-1]==word[0:len(word)-1]:
if items==target:
print "Target Achieved"
holderlist.append(items)
holderlist.append(changeling(items,target,steps-1))
else:
return None
i+=1
return holderlist
I receive a messy output:
[‘fine’, [‘line’, [‘lone’, [‘lose’, []]]], ‘fond’, []]
I get the answer I wanted, but I’m not sure how to a)clean it up, by not having lists within lists. and b)fond appears, because when find is called it gives fine and fond, fine is the one that ends up with the target word, and fond fails, but I’m not sure how to get rid of it once I’ve appended it to the holderlist.
Any help would be appreciated.
Cheers.
I’m not completely convinced that using
extendinstead ofappendwill solve all your problems, because it seems like that may not account for making a change that does not lead to solving the word and requires backtracking.If it turns out I am correct and the other answers don’t end up working, here is a recursive function that will convert your current result into what you are looking for: