我几乎完成了我对特定程序的编码。我只需要最后一件作品的帮助。 程序接受一个单词并将一个字母更改为更接近目标单词。 改变后的单词必须存在于我已经给出的字典中。
我的功能就是这样:
def changeling(word,target,steps):
holderlist=[]
i=0
if steps==0 and word!=target:
return None
return holderlist
if len(word)!=len(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"
holderlist.append(items)
flatten_result(holderlist,target)
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)
flatten_result(holderlist,target)
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)
flatten_result(holderlist,target)
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
我的助手功能是:
def flatten_result(nested_list, target):
if not nested_list:
return None
for word, children in zip(nested_list[::2], nested_list[1::2]):
if word == target:
return [word]
children_result = flatten_result(children, target)
if children_result:
return [word] + children_result
return None
flatten_result函数允许我将列表中的列表表示为单个列表,并通过我的程序回溯。如何在变换中实现展平结果?我现在只能在python shell中做到这一点。
答案 0 :(得分:1)
基本上,
def word_chain(chain_so_far, target, dictionary):
last_word = chain_so_far[-1]
if last_word == target:
print chain_so_far
return True
for word in dictionary:
if have_one_different_letter(word, last_word) and word not in chain_so_far:
word_chain(chain_so_far + [word], target)
将其称为word_chain(['love'], 'hate', your dict)
。如果您需要have_one_different_letter()
的帮助,请告诉我们。