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

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

    Here is a pure recursive way. You need to return the first smallest and the second smallest element in a tuple and so on.

    def smallest(int_list):
    
        if(len(int_list) == 2):
            if (int_list[0] >= int_list[1]):
                return (int_list[0],int_list[1])
            else:
                return (int_list[1],int_list[0])
        else:
            first_smallest,second_smallest = smallest(int_list[1:])
            current_elem = int_list[0]
            if(second_smallest <= current_elem):
                return (second_smallest,current_elem)
            else:
                if (current_elem<=first_smallest):
                   return (current_elem,first_smallest)
                else:
                   return (first_smallest,second_smallest)
    
    
    
    if __name__ == "__main__":    
        small = smallest([1,2,3,4])
        print small[1]
        //output 2 
    

提交回复
热议问题