python 3.2 - 使用递归在列表中找到第二小的数字 [英] python 3.2 - find second smallest number in a list using recursion

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

问题描述

所以我需要使用递归在整数列表中找到第二小的数字,但我一生无法设计出一种方法来做到这一点.我可以用这个来找到最小的数字:

So I need to find the second smallest number within a list of integers using recursion but I cannot for the life of me devise a way to do it. I can do it with to find smallest number using this:

def smallest(int_list):

    if(len(int_list) == 1):
        return int_list[0]
    else:
        a = smallest(int_list[1:])
        b = int_list[0]

        if(a <= b):
            return a
        else:
            return b

谁能指出我正确的方向?

Can anyone point me in the right direction?

推荐答案

这是一个不使用 min()sorted() 的简短实现.当列表中存在重复值时,它也有效.

Here is a short implementation that doesn't use min() or sorted(). It also works when there are duplicate values in the list.

def ss(e):
    if len(e)==2 and e[0]<=e[1]:return e[1]
    return ss(e[:-1]) if e[0]<=e[-1]>=e[1] else ss([e[-1]]+e[:-1])

print("The selected value was:", ss([5, 4, 3, 2, 1]))

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

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