Recursively find the kth largest int in list of list of int in Python

后端 未结 2 1534
悲哀的现实
悲哀的现实 2021-01-29 12:36

As a newbie in programming, I am trying to do a function to find the kth largest int in a list of list of ints. I tried list of ints before and it worked.

However, for

2条回答
  •  无人共我
    2021-01-29 13:15

    I wrote a generalized solution (you specify k) using extra arguments with default values to track both the smallest set of k found so far, and whether this was the top level of the recursion or a sub-level. Sub-levels return the current smallest subset, the top level returns the last entry (which is the kth smallest value). The smallest set of k is maintained using heapq's nsmallest method.

    import heapq
    
    def find_kth_smallest(k, a_list, smallest_k = [], top_level = True):
        l = len(a_list)
        if l > 1:
            l /= 2
            smallest_k = find_kth_smallest(k, a_list[:l], smallest_k, False)
            smallest_k = find_kth_smallest(k, a_list[l:], smallest_k, False)
        elif l < 1:
            return []
        else:
            if isinstance(a_list[0], list):
                smallest_k = find_kth_smallest(k, a_list[0], smallest_k, False)
            else:
                smallest_k.append(a_list[0])
                smallest_k = heapq.nsmallest(k, smallest_k)
        if top_level:
            return smallest_k[-1]
        else:
            return smallest_k
    
    print find_kth_smallest(3, [10, [9, 8, [[]]], [7, 6, [[5], 4, 3]], 2, 1]) # => 3
    

提交回复
热议问题