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

后端 未结 2 1533
悲哀的现实
悲哀的现实 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 12:53

    some hints:

    write a flatten function to convert list hierarchy to a single collection (with unique elements), sort and pick the k'th element.

    sample implementation

    def flatten(t):
         for e in t:
             if isinstance(e,list):
                 yield from flatten(e)
             else:
                 yield e
    
    
    
    set(flatten([[1,[]], 9, [[1], [3]], [4]]))
    
    {1, 3, 4, 9}
    

    of course, this approach is not the most efficient (perhaps it's the least efficient). You can return the first k elements from each sub level and prune at k'th level at each merge.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题