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

后端 未结 2 1535
悲哀的现实
悲哀的现实 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.

提交回复
热议问题