Search code examples
pythonrecursionpython-3.2

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


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 smallest number using this:

def smallest(int_list):

    if(len(int_list) == 1):
        return int_list[0]
    else:
        a = smallest(int_list[1:])
        b = int_list[0]

        if(a <= b):
            return a
        else:
            return b

Can anyone point me in the right direction?


Solution

  • 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]))