0

I have a list a = [5, 1, 2, 3, 4, 5] My program should return a list of the "indexes" of the maximum value, in this case [0, 5] but I'm using enumerate and not the actual index.

a = [5, 1, 2, 3, 4, 5]
a2 = enumerate(a)
result = list(a2)
print(result)

This now gives me [(0, 5), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] but I'm unsure of how to return 0 and 5 from here. I can find them individually by trying

print(result[0][0])
print(result[5][0])

but having trouble iterating over the list of tuples to find the first element where the second element is the maximum value. I'm thinking I need to use the max function but again unsure of the syntax this should take.

seevans38
  • 71
  • 5

3 Answers3

1

JUst get the max value of a list using max function. and then using enumerator match the max value with the value if the list . if they matched then store the index

max_value = max(a)
result = [index for index, value in enumerate(a) if value==max_value]

if dont want to use max function, and done the task in O(n) then

a = [5, 1, 2, 3, 4, 5,1,1,1,4,999999]

save_index = {}
largest = -99999999999 

for i, v in enumerate(a):
    if v>largest:
        largest=v
    if v not in save_index:
        save_index[v]=[i]
    else:
        save_index[v].append(i)

result = save_index[largest]
print(result)
# output 10
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
1

If you're allowed to use max it's very easy:

a = [5, 1, 2, 3, 4, 5]
results = [index for index, value in enumerate(a) if value == max(a)]

This is very inefficient as it runs max(a) on every iteration. Plus if you're unable to use max at all (because this sounds like an assignment) or if efficiency matters, you could do max first before the loop

results are [0, 5]

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
0

The good thing about lists is that you can use function max() and pass the list as a parameter to it. You can also use list comprehension to build your resulting output.

res = [i  for i in range(len(a)) if a[i]==max(a)]
Fatemeh Sangin
  • 558
  • 1
  • 4
  • 19