python - 在列表中查找最大值时出现意外值 None - Python 3 递归

标签 python list recursion

我正在尝试编写一个简单的递归函数来查找列表中的最大值,而不使用任何内置函数,“print”和“len”除外。我使用递归进行了简单的线性搜索,将列表中的每个成员与当前的 Max 进行比较。

x=[1,2,3]
Max=x[-1]

def Max_list(Max, x, c=2):

    if len(x)==1:
        return Max

    else:

        if c==(len(x)+1):
            print('hi')
            return Max

        elif x[len(x)-c]>Max:
            Max=x[len(x)-c]
            c+=1
            Max_list(Max, x, c)

        elif x[len(x)-c]<=Max:
            c+=1
            Max_list(Max, x, c)

print(Max_list(Max, x))

令我困惑的是我的程序打印“hi”(这是验证我的 if 条件是否满足),但返回 None。我本可以让它尝试返回任何内容,但它仍然会返回“无”。 我想知道如何显然地解决它,但如果有人能给我解释为什么我的代码在当前状态下总是返回 None,那就太好了。

最佳答案

正如一位用户在评论中指出的那样,您需要在对 Max_list(Max, x, c) 的两次调用中添加一个 return 语句。为什么会这样?

在 Python 中,如果调用的函数没有 return 语句,则默认返回值为 None。如果我们看看你的递归,它实际上在做的是:

    Initial Call:
    Max_list(3, x, 3)
              vvvvv
            Max_list(3, x, 4)
                      vvvvv
                     print('hi')
                     return 3 
            return None
    return None 

添加这些 return 语句后,我们得到了以下内容:

    Initial Call:
    Max_list(3, x, 3)
               vvvvvv
            Max_list(3, x, 4)
                      vvvvv
                     print('hi')
                     return 3 
            return the value of the above (3)
    return the value of the above (3)

关于python - 在列表中查找最大值时出现意外值 None - Python 3 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45465940/

相关文章:

python - 如何对数字列表求和?

c# - 通用 IList<T> 的 "type"是什么?

python - 在 Python 中线性化列表的最短方法

python - 按以下方式划分列表

python - django-pytest setup_method 数据库问题

python - Django Postgres 连接池

xmlstarlet递归地从多个文档中删除父元素

c - 在C中实例化临时静态列表头指针

perl - 在 perl 中重写递归函数,以便它可以在列表上下文中使用

python - conda SSL 错误