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
Simpler example than my comment:
def find_nth_smallest(n, int_list):
smallest = min(int_list)
if n <= 1:
return smallest
int_list = [v for v in int_list if v != smallest]
if int_list:
return max(find_nth_smallest(n - 1, int_list), smallest)
return None
Example:
Python 2.7.8 (default, Oct 20 2014, 15:05:19)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from kthTerm import find_nth_smallest
>>> import random
>>> random.seed()
>>> int_list = [random.randint(1, 100) for _ in range(20)]
>>> int_list
[68, 50, 6, 36, 98, 15, 81, 36, 13, 71, 76, 77, 69, 75, 79, 53, 26, 25, 18, 62]
>>> find_nth_smallest(2, int_list)
13
>>> sorted(int_list)
[6, 13, 15, 18, 25, 26, 36, 36, 50, 53, 62, 68, 69, 71, 75, 76, 77, 79, 81, 98]