函数意外返回None

-1 投票
1 回答
558 浏览
提问于 2025-04-17 21:51

好的,我完成了我一直在做的这段代码,但我遇到了一个大问题。它没有正确返回结果。

if is_word(wordlist, decodedText):
        print 'entered if statement'
        print answer
        return answer

这就是那段不工作的代码。程序的其他部分不重要。关于进入if语句的那行只是为了调试,让我知道确实进入了这个条件。接下来的打印语句是为了确认我的变量answer确实被赋值了,就像在程序的其他地方一样。

现在,这段代码给我的输出是:

进入了if语句 [(0, -6), (3, -18), (12, -16)] None

我还试着用type(answer)来确保没有什么奇怪的错误,但它只是说这是一个列表。

那么,为什么我得到的返回值是None呢??

answer = []
def find_best_shifts_rec(wordlist, text, start):
    """
    Given a scrambled string and a starting position from which
    to decode, returns a shift key that will decode the text to
    words in wordlist, or None if there is no such key.

    Hint: You will find this function much easier to implement
    if you use recursion.

    wordlist: list of words
    text: scambled text to try to find the words for
    start: where to start looking at shifts
    returns: list of tuples.  each tuple is (position in text, amount of shift)
    """
    global answer
    for shift in range(27):
        decodedText = apply_shift(text[start:], -shift)
        if is_word(wordlist, decodedText):
            print 'entered if statement'
            print answer
            return(answer)
        split = decodedText.split()
        if is_word(wordlist,split[0]) == True:
            answer.append((start, -shift))
            find_best_shifts_rec(wordlist, decodedText, (start+(len(split[0])+1)))
            break

print find_best_shifts_rec(wordlist, "JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?", 0)

这是我函数的其余部分。如果你需要查看其他内容,请告诉我。

1 个回答

3

问题在于你没有返回递归的结果……

if is_word(wordlist,split[0]) == True:
        answer.append((start, -shift))
        return find_best_shifts_rec(wordlist, decodedText, (start+(len(split[0])+1)))

撰写回答