python递归返回None类型 [英] python recursion return None type

查看:41
本文介绍了python递归返回None类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白,如何返回List 而不是None?

class foo():定义递归(aList):如果 isGoal(aList[-1]):返回一个列表对于 anotherList 中的项目:newList = list(aList)newList.append(item)递归(新列表)someList = [0]返回递归(someList)

基本上代码是记录所有路径(从0开始).谁先得到 100 将被退回.isGoal() 是检查路径的最后一项是否为 100.anotherList 是一个小的随机数列表(从 0 到 100).

解决方案

return 声明

当我刚开始学习递归时,这个问题实际上花了我很长时间才掌握.

在处理 Python 函数/方法时要记住的一件事是,无论如何它们总是 返回一个值.因此,假设您忘记在函数/方法的主体中声明 return 语句,那么 Python 会为您处理它并在其末尾执行 return None .

这意味着,如果您在函数体中搞砸了并且将 return 放错了位置或省略了它,而不是预期的返回,您的 print type(messed_up_function()) 将打印 NoneType.

递归修复

考虑到这一点,在处理递归时,首先要确保除了归纳案例之外还有一个基本案例,即防止无限递归循环.

接下来,确保您在两种情况下都返回,例如:

def recur(val):"""需要一个字符串将其从后到前返回"""断言类型(val)== str# 基本情况如果 len(val) == 1:返回值# 归纳案例别的:return val[-1] + recur(val[:-1]) # 一个字符一个字符地反转

所以它总是returns并且是100%无限递归证明,因为它在每个归纳步骤都有一个有效的基本情况和递减的长度.

用于调试递归函数的堆栈查看器

如果我们要在基本案例的开头添加 assert False 来运行 recur('big'),我们将拥有以下堆栈结构:>

从中我们可以看出,在每一个递归步骤,我们都有val,它是这个函数的唯一参数,越来越小,直到碰到len(val) ==1 然后它到达最终返回,或者在这种情况下 assert False.所以这只是调试递归函数/方法的一种方便的方法.在 IDLE 中,您可以通过调用 Debug > 来访问这样的视图.堆栈查看器在shell中.

I don't get it, how can i return a List instead of a 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). Whoever gets 100 first will be returned. 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).

解决方案

return statement

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. 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.

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.

Recursion fix

Now with that in mind, when dealing with recursion, first make sure you have a base case besides the inductive case, I.e. 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 returns and is 100% infinite recursion proof because it has a valid base case and a decremented length at each inductive step.

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:

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. 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.

这篇关于python递归返回None类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆