python 3.2 - find second smallest number in a list using recursion

后端 未结 7 1683
谎友^
谎友^ 2020-12-22 08:32

So I need to find the second smallest number within a list of integers using recursion but I cannot for the life of me devise a way to do it. I can do it with to find smalle

7条回答
  •  清酒与你
    2020-12-22 09:06

    Here's an approach that doesn't blow the stack for large lists. It would be better to manage the search endpoints manually rather than using slicing which introduce copying.

    import random
    
    def min2(xs):
        if len(xs) < 3: return xs
        n = len(xs) // 2
        return sorted(min2(xs[:n]) + [xs[n]] + min2(xs[n+1:]))[:2]
    
    tk = range(100000)
    random.shuffle(tk)
    print min2(tk)
    

提交回复
热议问题