简体   繁体   English

python递归返回None类型

[英]python recursion return None type

I don't get it, how can i return a List instead of a None ?我不明白,如何返回List而不是None

class foo():
    def recursion(aList):
        if isGoal(aList[-1]):
            return aList
        for item in anotherList:
            newList = list(aList)
            newList.append(item)
            recursion(newList)

    someList = [0]
    return recursion(someList)

Basically the code is to record all paths (start at 0).基本上代码是记录所有路径(从0开始)。 Whoever gets 100 first will be returned.谁先得到 100 将被退回。 isGoal() is to check if last item of the path is 100. And anotherList is a small list of random numbers (from 0 to 100). isGoal()是检查路径的最后一项是否为 100。 anotherList是一个小的随机数列表(从 0 到 100)。

return statement return语句

This problem actually took me quite a while to grasp when I first started learning recursion.当我第一次开始学习递归时,这个问题实际上花了我很长时间才掌握。

One thing to keep in mind when dealing with Python functions/methods is that they always return a value no matter what.在处理 Python 函数/方法时要记住的一件事是,无论如何它们总是return一个值。 So say you forget to declare a return statement in the body of your function/method, Python takes care of it for you then and does return None at the end of it.因此,假设您忘记在函数/方法的主体中声明return语句,那么 Python 会为您处理它并在它的末尾return None

What this means is that if you screw up in the body of the function and misplace the return or omit it, instead of an expected return your print type(messed_up_function()) will print NoneType .这意味着,如果您在函数体中搞砸了并且错误地放置了return或省略了它,那么您的print type(messed_up_function())将打印NoneType而不是预期的返回NoneType

Recursion fix递归修复

Now with that in mind, when dealing with recursion, first make sure you have a base case besides the inductive case , Ie to prevent an infinite recursive loop.现在考虑到这一点,在处理递归时,首先确保除了归纳案例之外还有一个基本案例,即防止无限递归循环。

Next, make sure you're returning on both cases, so something like this:接下来,确保你在这两种情况下都返回,所以是这样的:

def recur(val):
    """
    takes a string
    returns it back-to-front
    """
    assert type(val) == str
    # the base case
    if len(val) == 1:
        return val
    # the inductive case
    else:
        return val[-1] + recur(val[:-1]) # reverses a string char by char

So what this does is it always return s and is 100% infinite recursion proof because it has a valid base case and a decremented length at each inductive step.所以它所做的是它总是return s 并且是 100% 无限递归证明,因为它在每个归纳步骤都有一个有效的基本情况和递减的长度。

Stack Viewer to debug recursive functions用于调试递归函数的堆栈查看器

In case we would run recur('big') with the added assert False at the start of the base case, we would have this stack structure:如果我们在基本情况开始时使用添加的assert False运行recur('big') ,我们将拥有以下堆栈结构:

范围

From it we can see that at each recursive step, we have val , which is the only parameter of this function, getting smaller and smaller until it hits len(val) == 1 and then it reaches the final return, or in this case assert False .从它我们可以看到,在每个递归步骤中,我们都有val ,它是这个函数的唯一参数,它越来越小,直到遇到len(val) == 1 ,然后到达最终返回,或者在这种情况下assert False So this is just a handy way to debug your recursive functions/methods.所以这只是调试递归函数/方法的一种方便的方法。 In IDLE you can access such a view by calling Debug > Stack Viewer in the shell.IDLE 中,您可以通过在 shell 中调用Debug > Stack Viewer来访问这样的视图。

The function is this:功能是这样的:

def recursion(aList):
    if isGoal(aList[-1]):
        return aList
    for item in anotherList():
        newList = list(aList)
        newList.append(item)
        recursion(newList) # here you ignore what recursion returns
    # when execution reaches this point, nothing is returned

If execution reaches my added comment, after the for loop completes, the function exits and nothing is returned.如果执行到达我添加的注释,则在 for 循环完成后,函数退出并且不返回任何内容。 And when you exit a function without having executed a return statement, None is returned.当你在没有执行return语句的情况下退出函数时, None被返回。 You must make sure that you return something from the recursive function.您必须确保从递归函数中返回一些内容。

I can't advise you on how to re-write the function since I don't know what it is trying to do.我无法建议您如何重写该函数,因为我不知道它要做什么。 It's very far from obvious to me how it needs to be changed.对我来说,它需要如何改变还很不明显。 However, what I can say with complete confidence is that you must return something!但是,我可以完全自信地说,您必须返回一些东西!

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

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