I was wondering how to find the second smallest number from a user-input list with def functions. Also, WITHOUT using any sorting functions, imported modules, and min() and max() functions, how would I find the numbers by using just loops and relational operators?
Here's my following code (I only have finding the smallest number so far...):
def second_smallest():
smallest = second_smallest[0]
for i in second_smallest[1:]:
if smallest > i:
smallest = i
return smallest
Examples of following tests are shown:
print(second_smallest([5, 7, 2, 1, 3]))
2
print(second_smallest([100, 51, 31, 5, 10]))
10
Thanks!
SO Isn't really for homework, but it sounds like you have had a think about this. There are two situations to consider and both require knowledge of the smallest:
I've expressed this in the code below. We've had to keep the existing smallest tracking and add to it.
Note, technically there might not be a second smallest, if you provide a list of the same numbers. e.g.
[4,4,4,4]
. The code above will return 4, but really, it's an error case that should be considered and dealt with.This is a simple approach that would break down for a question like "what is the nth smallest?" At which point you have basically created a sorting algorithm.
Please note that this returns
float('inf')
(initial value) for lists withlen(lst) <= 1
as there is no second item in the list.