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

后端 未结 7 1685
谎友^
谎友^ 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:09

    Here:

    def r_sort(a_list, ind):
        def rf(list_to_be_sorted, list_already_sorted):
            li = []
            if len(list_to_be_sorted) == 0:
                return list_already_sorted
            else:    
                x = min(list_to_be_sorted)    
                list_to_be_sorted.remove(x)
                li.append(x)
                return rf(list_to_be_sorted, list_already_sorted + li)
        return rf(a_list, [])[ind]
    
    >>> r_sort([1,10,9,5,55,3,2], 1)  
    2
    

提交回复
热议问题