[Tutor] Getting greatest 3 numbers from list

Alan Gauld alan.gauld at yahoo.co.uk
Mon Feb 21 08:23:05 EST 2022


On 21/02/2022 11:29, Manprit Singh wrote:

> solution given below:
> ls = [2, 4, 9, 6, 3, 9, 6, 1]
> sorted(set(ls))[-3:]
> 
> gives the right answer
> 
> [4, 6, 9]

Yes, and that's almost certainly the best way to do it.


> Tried it with a for loop, just thinking why i am producing  a sorted list , for
> only getting largest 3 items

Why not, it is the simplest approach?

> lmax = []
> ls = [2, 4, 9, 6, 3, 9, 6, 1]
> for _ in range(3):
>     mx = ls[0]
>     for ele in ls[1:]:
>         if ele > mx and ele not in lmax:
>             mx = ele
>     lmax.append(mx)
> print(lmax)

This loops over ls 3 times. That's not necessary.
One alternative is:

>>> ls = [2, 4, 9, 6, 3, 9, 6, 1]
>>> lmax = ls[:3]
>>> for n in ls[3:]:
       if n in lmax: continue
       for i,j in enumerate(lmax):
           if n > j:
              lmax[i] = n
              break

Which should be faster, and at least no slower.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list