Thanks to stack overflow I’m almost done with a programming problem that’s been driving me crazy. It’s recursive, and here’s what it looks like:
def changeling(word,target,steps):
x=word
z=target
if steps==0:
return []
if x==z:
return [z]
if len(word)!=len(target):
print "error"
return None
i=1
if lookup(z[0]+x[1:]) is True and z[0]+x[1:]!=x :
word=z[0]+x[1:]
while i!=len(x):
if lookup(x[:i-1]+z[i-1]+x[i:]) and x[:i-1]+z[i-1]+x[i:]!=x:
word=x[:i-1]+z[i-1]+x[i:]
i+=1
if lookup(x[:len(x)-1]+z[len(word)-1]) and x[:len(x)-1]+z[len(x)-1]!=x :
word=x[:len(x)-1]+z[len(word)-1]
return [x]+changeling(word,target,steps-1)
if I enter:
changeling("find","lose"4)
I receive:
['find', 'fine', 'line', 'lone', 'lose']
Which is the exact output I want. My next step in the program is this. If a word cannot be changed to the target word in a certain number of steps, the function just returns None. So if I were to input:
changeling(“find”,”lose”,3)
I should receive nothing, but instead I receive:
['find', 'fine', 'line']
I’m not quite sure how to do this, any help would be appreciated.
Instead of returning immediately the recursion, proceed as follow:
The problem with your original version is that you return what has been computed with, appended, the following steps. If you can’t find a good word to continue the chain, then your program outputs
None, thus you return statement is composed of a list of valid steps + None, which is equivalent to only the list of valid steps. Here, all we do is check first if the following step can be achieved, if not we returnNoneonly, and if yes, then we return everything.