Finding the second smallest number using loops in

2020-04-18 04:25发布

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!

2条回答
贪生不怕死
2楼-- · 2020-04-18 04:48

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:

  1. the second smallest is seen before the smallest is seen, in which case the second smallest will be the value that smallest held before it held its final value.
  2. The second smallest is seen after the smallest is seen, in which case the second smallest will be bigger than it, but smallest won't be smaller than it OR equal to it

I've expressed this in the code below. We've had to keep the existing smallest tracking and add to it.

def second_smallest():
    smallest = float("inf")
    second_smallest = float("inf")
    for i in second_smallest:
        if smallest > i:
            second_smallest = smallest
            smallest = i
        elif second_smallest > i and not smallest == i:
            second_smallest = i
    return second_smallest

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.

查看更多
放荡不羁爱自由
3楼-- · 2020-04-18 05:03
>>> 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.

查看更多
登录 后发表回答