Reputation: 5452
Here is my function:
def listMaxInd(l):
max_val = l[0]
maxIndex = 0
count_assigment = 1
count_comparison = 0
for i in range(1,len(l)):
count_comparison=count_comparison+1
if l[i]>max_val:
max_val=l[i]
maxIndex=l.index(max_val)
count_assigment = count_assigment + 1
return maxIndex,count_assigment,count_comparison
I want to find maximum value of a list by only assigning indices, and not by assigning the values.
In my version I am assigning values still. Is it possible to find the maximum without this?
Upvotes: 1
Views: 475
Reputation: 1124538
If you need to use a loop and cannot use the max()
function, then you are stuck with assigning at the very least the index pointing at the maximum found so far:
max_index = 0
for i, value in enumerate(l):
if value > l[max_index]:
max_index = i
When the loop completes, max_index
points to the (first occurrence of) the maximum value in l
. enumerate()
is a more compact and efficient method of generating indices in a loop, together with the values iterated over.
The more efficient method would be to use the max()
function with a key:
max_index = max(range(len(l)), key=l.__getitem__)
This will return the (first) index of the maximum value in list l
; given a list of indices (range(len(l))
), it'll find the index for which l.__getitem__()
returns the highest value.
Upvotes: 2