In: Computer Science
Write a function argmax(somelist=[]) to return the index of the largest number in a numerical list, or None if the list is empty. If there are ties, then return the index of the first occurrence of the largest number. Sample: argmax([2, 2, 4, 4, 1]) returns 2. in python program
def argmax(x):
if x==[]: #check whether list is empty. or check
len(x)==0
return None #if empty,"None" is
returned
largest=x[0] #initally, set first element as
largest
for i in x: # search for largest element
if(largest<i): # if the current element i
>largest, then set it as the largest
largest=i
position =x.index(largest) #find the index of largest
element
return position
n=int(input("enter the lnumber of elements"))
x=[ ]
for i in range(0,n):
x.append(int(input("enter the element"))) #append each input
element to the list x
print("The input list is",x)
print("index of largest element is::",argmax(x))
Note:: The index()
method returns the
position at the first occurrence of the specified
value.
Without using index, the function can be written as
def argmax(x):
if x==[]: #check whether list is empty. or check
len(x)==0
return None #if empty,"None" is returned
largest=x[0] #initally, set first element as
largest
position=0
for i in range(0,len(x)-1): # search for largest element ,
i varies from 0 to length(x)-1
if(largest<x[i]):
largest=x[i]
position=i
#position =x.index(largest)
return position