繁体   English   中英

函数意外返回None

[英]Function returns None unexpectedly

好。 因此,我完成了我一直在努力的这段代码,但是我遇到了一个主要问题。 我没有正确返回。

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

这是不起作用的代码。 该程序的其余部分不是必需的。 输入if语句的行只是一个调试,因此我实际上会知道它确实输入了。 下一个打印语句是确保我的变量答案实际上已分配给某项内容,例如程序中的其他位置。 现在,这就是代码给我的:

entered if statement [(0, -6), (3, -18), (12, -16)] None

我还尝试使用type(answer)来确保我没有看到一些奇怪的错误,但这只是说这是一个列表。

那么,为什么我会得到无回报?

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)

这是我其余的功能。 让我知道您是否还有其他需要看的地方。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM