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
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