Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find k biggest numbers from a list of n numbers assuming n > k

Tags:

python

list

max

I am looking for some code in Python which could return k largest numbers from an unsorted list of n numbers. First I thought to do this by sorting the list first, but this might turn out to be very bulky.

For example the list from which I want to find k largest number be list1

> list1 = [0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]

Here n = 7 and if k = 3, that is if I want to find 3 largest numbers from a list of 7 numbers then output should be 0.5, 0.7, 0.5

How can this be done?

like image 554
Lokesh Avatar asked Jul 28 '13 09:07

Lokesh


People also ask

How do I find the largest n value in a list Python?

You can also use the heapq module to get the n-largest/smallest elements from a list. Use the nlargest() and nsmallest() functions of the heapq module. In this case, the original list is not changed. The first argument is the number of elements to be returned, and the second is the target iterable (e.g., list).

How do you find the top 3 values in Python?

If you want to get the indices of the three largest values, you can just slice the list. It also supports sorting from smallest to largest by using the parameter rev=False .


3 Answers

Python has all batteries included - use heapq module :)

from heapq import nlargest

data = [0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]
print nlargest(3, data)

it's also faster than sorting the whole array, because it's using partial heapsort

like image 183
Roman Pekar Avatar answered Nov 15 '22 22:11

Roman Pekar


It can be done like this:

>>> list1
[0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]
>>> list2 = list1[:] #make a copy of list1
>>> k = 3
>>> result = []
>>> for i in range(k):
        result.append(max(list2)) #append largest element to list of results
        list2.remove(max(list2)) # remove largest element from old list
>>> result
[0.7, 0.5, 0.5]
>>> 
like image 21
Pawel Miech Avatar answered Nov 15 '22 22:11

Pawel Miech


Assuming you don't want to modify list1, you make a sorted copy:

In [1]: list1 = [0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]

In [2]: list2 = sorted(list1)

In [3]: list2
Out[3]: [0.3, 0.3, 0.3, 0.4, 0.5, 0.5, 0.7]

In list2, the largest numbers are the last numbers, so we'll use slicing:

In [4]: list2[-3:]
Out[4]: [0.5, 0.5, 0.7]

The links I've added point to Pythons documentation. As a beginner, you should start with having a look at the tutorial. After that, the library reference is what you'll be needing most, because the large standard library is one of the things that makes python so nice.

like image 38
Roland Smith Avatar answered Nov 15 '22 22:11

Roland Smith