Две функции в рекурсивных функциях? - PullRequest
0 голосов
/ 27 марта 2012

Я почти закончил кодирование для конкретной программы, которая у меня есть. Мне просто нужна помощь с одним последним произведением. Программа берет слово и меняет одну букву, чтобы более близко походить на целевое слово. Измененное слово должно существовать в словаре, который мне дали.

моя функция такова:

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.

1 Ответ

1 голос
/ 27 марта 2012

В основном,

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().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...