rlo5029 rlo5029 - 3 days ago 4
Python Question

Python: Function returning highest value in list without max()?

I need to write a function that takes a list of numbers as the parameter and returns the largest number in the list without using

max()
.

I've tried:

def highestNumber(l):
myMax = 0
if myMax < l:
return myMax

return l


print highestNumber ([77,48,19,17,93,90])


...and a few other things that I can't remember. I just need to understand how to loop over elements in a list.

Answer
def highestNumber(l):
    myMax = l[0]
    for num in l:
        if myMax < num:
            myMax = num
    return myMax


print highestNumber ([77,48,19,17,93,90])

Output

93

Or You can do something like this

def highestNumber(l):
    return sorted(l)[-1]

Or

def highestNumber(l):
    l.sort()
    return l[-1]
Comments