I want to return the 2nd smallest element from a nested list using recursion and no built in functions. i.e.
>>>ss([[[1,3],[2],3]])
2
I know how to get the maximum and minimum of such lists but I'm having trouble keeping track of the second smallest value.
What I wrote so far, which does return the correct smallest value but doesn't work for second smallest.
def ss(L):
smallest = L[0]
while type(smallest) == type([]):
smallest = smallest[0]
second_smallest = smallest
for element in L:
if type(element) == type([]):
current = ss(element)
if current > smallest and current < second_smallest:
second_smallest = current
if current < smallest and current < second_smallest:
second_smallest = smallest
smallest = current
else:
if smallest < element and element < second_smallest:
second_smallest = element
if smallest > element and second_smallest > element:
second_smallest = smallest
smallest = element
return second_smallest
Is there a way to make this work or should I look for a different approach?