Link to home
Start Free TrialLog in
Avatar of Michael Noze
Michael Noze

asked on

Find the highest, second highest, third highest,

Hi Experts,

Is there a way to find the highest number in a list then the second highest then the third highest in a list without using sort

Thank you.
Avatar of John Tsioumpris
John Tsioumpris
Flag of Greece image

You can sort the list descending
list.sort(reverse=True)

Open in new window

Check this small tutorial for start
Avatar of Michael Noze
Michael Noze

ASKER

Hi John,
Is there a way to do it without using sort?
What do you mean ? can you give a small example
You could sort the list and then extract the top n values like this.

n=3

mylist = [12,2,3,2,324,3]

mylist.sort(reverse=True)

print(mylist[:n]

Open in new window

For example:

[10, 3, 4 , 1, 8]

Would be

[10, 3, 4, 1, 8]
[10, 8, 3, 4, 1]
[10, 8, 4, 3, 1]
It looks like you are sorting, not getting the largest, second largest, etc items from the list.
I think he wants to do it one step a time...
Probably the idea is to sort it first...pick first 3 as maximum1,maximum2,maximum3 (max1>max2>max3)
and then replace the list elements according to the above.
Yes, that is the idea @John.
so first part is done
This non-sorting code will get you the top three largest values in a list (a)
large = [max(a)]
large.append(max(a, key = lambda x: x not in large))
large.append(max(a, key = lambda x: x not in large))
print(large)

Open in new window

But he wrote:
without using sort
We could employ set()
b = list(set(a))
b[::-1]

Open in new window

We could move the .append() statement in my earlier comment into a loop that would stop when we didn't have any new values coming from the max() function.
This seems a bit like an insertion sort.
ASKER CERTIFIED SOLUTION
Avatar of John Tsioumpris
John Tsioumpris
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial