Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

index, reps, and maximum number in a list python

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading