函数意外返回无

时间:2014-03-11 21:35:36

标签: python

确定。所以我完成了我一直在研究的这段代码,但是我遇到了一个重大问题。我没有正确回归。

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

这是一段不起作用的代码。该计划的其余部分是不必要的。关于输入if语句的行只是一个调试,所以我实际上知道它确实输入了。下一个打印声明是为了确保我的变量答案实际上被分配给某个东西,就像它在程序的其他地方一样。 现在,这就是代码给我的东西:

entered if statement [(0, -6), (3, -18), (12, -16)] 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 个答案:

答案 0 :(得分:3)

问题是你没有返回你的递归结果....

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