How do I return a list of the 3 lowest values in another list

后端 未结 5 1874
情话喂你
情话喂你 2021-01-13 21:00

How do I return a list of the 3 lowest values in another list. For example I want to get the 3 lowest values of this list:

in_list = [1, 2, 3, 4, 5, 6]
inpu         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-13 21:30

    Sorting is the reasonable approach. If you care about asymptotic complexity though, you'd want to do this in time O(n) and space O(1).

    def k_min(values, k):
        return sorted(values)[:k]
    

    Calling to sorted() can give you time only O(n*log n) and space O(n), so to achieve O(n) time and O(1) space, different approach is needed.

    For that, you'd iterate through the list (that's where O(n) comes from) and keep track of the k minimal elements seen so far, which can be done in constant time (since k is here a constant).

    For keeping track of the minimal elements, you can use a heap (module heapq), or a list. In case of list, time is O(nk) and in case of heap time is O(nlog k). In any case, because k is for you a constant, this whole thing will end up linear in n in total.

    Using a list (which is bit simpler to use than the heap, though of course bad if k is large), it may look like this

    def k_min(values, k):
        minima = []  # len(minima) <= k + 1
        for v in values:
            minima.append(v)
            if len(minima) > k:
                minima.remove(max(minima))  # O(k) == O(1)
        return minima
    

提交回复
热议问题