简体   繁体   English

函数意外返回None

[英]Function returns None unexpectedly

Ok. 好。 So I finished this piece of code I have been working on, but I have a major problem. 因此,我完成了我一直在努力的这段代码,但是我遇到了一个主要问题。 I doesn't return correctly. 我没有正确返回。

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

this is the piece of code that isn't working. 这是不起作用的代码。 The rest of the program isn't necessary. 该程序的其余部分不是必需的。 The line about entering the if statement was just a debug, so I would actually know that it did enter. 输入if语句的行只是一个调试,因此我实际上会知道它确实输入了。 The next print statement was to make sure that my variable answer actually was assigned to something, like it was elsewhere in the program. 下一个打印语句是确保我的变量答案实际上已分配给某项内容,例如程序中的其他位置。 Now, this is what the code is giving me: 现在,这就是代码给我的:

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

I also tried using type(answer) to make sure that I didn't have some weird bug I wasn't seeing, but it was just saying it was a list. 我还尝试使用type(answer)来确保我没有看到一些奇怪的错误,但这只是说这是一个列表。

So, why am I getting a None return?? 那么,为什么我会得到无回报?

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)

This is the rest of my function. 这是我其余的功能。 Let me know if there is something else you need to see. 让我知道您是否还有其他需要看的地方。

the problem was you were not returning your recursive result .... 问题是您没有返回递归结果....

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