Python:递归函数来查找列表中的最大数 [英] Python: Recursive function to find the largest number in the list

查看:41
本文介绍了Python:递归函数来查找列表中的最大数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据教科书 Zelle Python Programming 进行实验室工作

I'm trying to do a lab work from the textbook Zelle Python Programming

问题要求我编写并测试递归函数 max() 以找到列表中的最大数.最大值是第一项中的较大者,其他项中的最大值项目."课本上的问题我不太明白.

The question asked me to "write and test a recursive function max() to find the largest number in a list. The max is the larger of the first item and the max of all the other items." I don't quite understand the question from the textbook.

def Max(list):
    if len(list) <= 1:
        else:
            return list[0]
        else:
            m = Max(list[1:])
            return m if m > list[0] else list[0]

def main():
    list = eval(raw_input(" please enter a list of numbers: "))
    print("the largest number is: ", Max(list))

main()

或者我想打开一个包含数字的 txt 文件,然后使用递归?

Or maybe I'm suppose to open a txt file with numbers in it and then use recursive?

我相信递归是这样的

def function()
> if something:
>>return 0
>else:
>>return function()

推荐答案

您对递归工作原理的理解似乎很好.

Your understanding of how recursion works seems fine.

你的 if 块搞砸了,你有两个 else 对一个 if 并且对齐失败了.您需要删除第一个 else 并取消缩进 if 一层以下的所有内容.例如:

Your if-block is messed up, you have two elses to one if and the alignment is out. You need to remove your first else and un-indent everything below the if one level. eg:

def Max(list):
    if len(list) == 1:
        return list[0]
    else:
        m = Max(list[1:])
        return m if m > list[0] else list[0]

def main():
    list = eval(raw_input(" please enter a list of numbers: "))
    print("the largest number is: ", Max(list))

main()

这篇关于Python:递归函数来查找列表中的最大数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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