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!
解决方案>>> def second_smallest(lst):
... first = second = float("inf")
... for num in lst:
... if num < first:
... second, first = first, num
... elif first < num < second:
... second = num
... return second
Please note that this returns float('inf') (initial value) for lists with len(lst) <= 1 as there is no second item in the list.