在Python中使用循环找到第二小的数字 [英] Finding the second smallest number using loops in python

查看:1002
本文介绍了在Python中使用循环找到第二小的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从def函数的用户输入列表中找到第二小的数字。另外,使用任何排序函数,导入模块和min()和max()函数的 WITHOUT ,我如何通过使用循环和关系运算符来查找数字?

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

感谢!

推荐答案

>>> 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

请注意,对于含有 len(lst)的列表,这返回 float('inf') (初始值) = 1 ,因为列表中没有第二项。

Please note that this returns float('inf') (initial value) for lists with len(lst) <= 1 as there is no second item in the list.

这篇关于在Python中使用循环找到第二小的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆