1

Given a list of integers, find maximum value, number of maximum elements and index of last maximum in it.

so I'm trying to find the index of the last maximum, and I need to use sort, which doesn't preserve the order of the list, how do I fix this error?

a = [int(s) for s in input().split()]
a.sort()
if a.count(max(a)) == 1:
    print(max(a), a.count(max(a)), a.index(max(a)))
else:
    print(max(a), a.count(max(a)), len(a)-1)
Meno
  • 120
  • 8

1 Answers1

0

The following code should work to print out the index of the maximum value of the list:

a = [int(s) for s in input().split()]
if a.count(max(a)) == 1:
  print(a.index(max(a)))
else:
  ind = len(a) - 1
  while a[ind] != max(a):
    ind -= 1
  print(ind)

Note: We don't need to sort a because the max() function will find the maximum of the list regardless of if it is sorted or not.

If only one maximum value occurs in the list, we just use the .count() function as you did.

If there are multiple maximum values and we want to print out the last one that appears, we can use a while loop to iterate backwards through the list until we find one.

I hope this helped! Please let me know if you have any further questions!

Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14