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

后端 未结 7 1701
谎友^
谎友^ 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 08:56

    Here is a short implementation that doesn't use min() or sorted(). It also works when there are duplicate values in the list.

    def ss(e):
        if len(e)==2 and e[0]<=e[1]:return e[1]
        return ss(e[:-1]) if e[0]<=e[-1]>=e[1] else ss([e[-1]]+e[:-1])
    
    print("The selected value was:", ss([5, 4, 3, 2, 1]))
    

提交回复
热议问题