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

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

    This should work. get_smallest_two_items() returns a tuple with the smallest 2 elements out of the 3 inputted. Implementing it should be trivial. Also note that this assumes the minimum length of the list is 2.

    def smallest(int_list):
       smallest_two = smallest_helper(int_list)
       return smallest_two[0] if smallest_two[0]<=smallest_two[1] else smallest_two[1]
    
    def smallest_helper(int_list):
    
      if(len(int_list) == 2):
        return (int_list[0],int_list[1])
      else:
        a_b = smallest(int_list[1:])
        a = a_b[0]
        b = a_b[1]
        c = int_list[0]
    
        return get_smallest_two_items(a,b,c)
    
    0 讨论(0)
提交回复
热议问题