[Tutor] Getting the highest numbers from a list

Ignacio Vazquez-Abrams ignacio@openservices.net
Mon, 27 Aug 2001 15:05:04 -0400 (EDT)


On Mon, 27 Aug 2001, David L. Lerner wrote:

> Is there a simple way to get the _n_ highest numbers from an unordered list?
>
> I have a long list that I randomly generated.  I need the five highest
> numbers.  I have another long list, also randomly generated, from which I
> need the _sum_ of the five highest numbers
>
> I know max(start_list) will give me the single highest number in the list
> "start_list".  How do I get the five highest numbers?
>
>
> Here's my solution, but it's ugly.

Here are my changes:

> -----------------------------

import operator

> start_list=[7, 6, 6, 15, 9, 0, 9, 10, 12, 10, 11, 15, 2, 8, 0, 4, 10, 1, 3,
> 14]
> ## start_list is the original version of the first list.
>
> start_list2=[2, 13, 0, 10, 10, 3, 3, 5, 9, 11, 10, 5, 9, 14, 4, 6, 5, 3, 11,
> 11, 9]
> ## start_list2 is the original version of the second list

#   in start_list2.  I only use it to find the last five.

>
> print 'The first list:', start_list
> print 'The second list:', start_list2
>
> start_list.sort()

high_list=start_list[-5:]

> high_list.reverse()
>
> start_list2.sort()

high_list2=start_list2[-5:]
high_sum=reduce(operator.add, high_list2)

> print 'The five highest numbers in the first list:', high_list
> print 'The sum of the five highest numbers in the second list:', high_sum
>
> -----------------------------
> Thank you
>
> David L. Lerner
> dell2100@prodigy.net
> Often, the most striking and innovative solutions come from realizing that
> your concept of the problem was wrong.
> Eric Steven Raymond

Better? :)

-- 
Ignacio Vazquez-Abrams  <ignacio@openservices.net>