Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Recursive function to find the largest number in the list

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

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()

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

I believe recursive works like this

def function()
> if something:
>>return 0
>else:
>>return function()
like image 538
Jimmy Ly Avatar asked Nov 28 '22 16:11

Jimmy Ly


1 Answers

Your understanding of how recursion works seems fine.

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()
like image 114
jam Avatar answered Dec 06 '22 19:12

jam