[Tutor] Getting the highest numbers from a list

David L. Lerner dell2100@prodigy.net
Mon, 27 Aug 2001 14:20:57 -0400


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.

-----------------------------

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.
high_list=[]      ## high_list will be a list of the five highest numbers in
start_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
high_list2=[]      ## high_list2 will be a list of the five highest numbers
in start_list2.  I only use it to find the last five.
high_sum= 0      ## high_sum will be the sum of the five highest numbers in
start_list2

print 'The first list:', start_list
print 'The second list:', start_list2


start_list.sort()
for r in range (-1,-6,-1):
        high_list.append (start_list[r])
high_list.reverse()


start_list2.sort()
for r in range (-1,-6,-1):
        high_list2.append (start_list2[r])
        high_sum = high_sum + (start_list2[r])

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