-1

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.

4

3 回答 3

6
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]
于 2013-10-19T17:53:39.803 回答
2

You need to loop over all values to determine the maximum; keep track of the maximum so far and return that after completing the loop:

def highestNumber(l):
    myMax = float('-inf')
    for i in l:
        if i > myMax:
            myMax = i
    return myMax

Here, float('-inf') is a number guaranteed to be lower than any other number, making it a great starting point.

The for construct takes care of all the looping; you do that directly over the elements of l, i is assigned each element of the sequence, one by one.

Your code forgets to loop, tests the whole list against 0 and returns the whole list if the test failed.

于 2013-10-19T17:52:21.450 回答
0

function to find maximum in a list without using predefined functions

def max_len_list(temp):
    i=1
    for each in temp:
        while i < max_len:
            comp=each;
            if comp > temp[i]:
                i=i+1;
            elif temp[i] > comp:
                comp=temp[i];
                i=i+1
        return comp
list1 = [];
max_len=3;
try:
    while len(list1) < max_len :
        no = int(input("enter a number\n"));
        list1.append(no);
except:
    print "enter number not string"
max_no=max_len_list(list1);
print max_no
于 2016-12-01T06:26:25.117 回答