我遇到程序问题,程序只需一个单词,一次更改一个字母,将该单词转换为目标单词。虽然,请记住,根据我给出的单词词典,转换后的单词必须是合法的单词。
我无法弄清楚如何使其递归。该计划对必须采取的步骤数量有限制。
编辑:我不允许制作持有人全球。
我的代码到目前为止:
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)
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)
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)
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)
changeling(items,target,steps-1)
else:
changeling(None,None,steps-1)
i+=1
return holderlist
我最大的问题是,每当我尝试递归程序时,我的持有列表持有者列表都会刷新。
如果我手动输入数据,我可以解决它。这就是我希望程序做的事情:
changeling("find","lose",4)
gives me:
['fine','fond']
the program should then do:
changeling('fine','lose',3)
gives me:
['line']
changeling('line','lose',2)
gives me:
['lone']
changeling('lone','lose',1)
gives me:
['lose']
Target Achieved
答案 0 :(得分:1)
可能像
def distx(w1,w2):
if len(w1) != len(w2):return 100000
score=0
for i in range(len(w1)):
score += int(w1[i] != w2[i])
return score
word_list = ["fine","fond","line","lose","lone"]
def changeling(guess,target,steps):
my_steps = []
print "Guess:",guess
if target == guess:return [guess]
try:word_list.remove(guess)
except:pass
my_steps.append(guess)
if target != guess and steps >= 0:
this_step = []
one_step_away = [w for w in word_list if distx(guess,w) == 1]
for k in one_step_away:
print " %s->"%guess,k
this_step.append(changeling(k,target,steps-1))
my_steps.append( this_step )
return my_steps
tmp = changeling("find","lose",4)
print tmp