max of a list in python -
so need write , test function returns index of largest element in list (or, if several elements have largest value, index of first 1 of them) , i'm not allowed use max function. appreciated!
def largestelementindex(lst): x=0 maxnum=0 while x+1 < len(lst): if lst[x] > maxnum: maxnum=x x+=1 return maxnum print "program output" indexofmax = largestelementindex([1, 4, 3, 3, 2]) print 'index of max value is',indexofmax
you need store largest number index:
def largestelementindex(lst): x=0 maxnum=0 maxindex=0 while x < len(lst): if lst[x] > maxnum: maxindex=x maxnum=lst[x] x+=1 return maxindex
i'd use for
loop:
def largestelementindex(lst): max_index = 0 max_value = lst[0] index, value in enumerate(lst) if value > max_value: max_index = index max_value = value return max_index
to max
, use enumerate
same way:
max_index = max(enumerate(lst), key=lambda pair: pair[1])[0]
Comments
Post a Comment