小编VD1*_*421的帖子

使用递归返回嵌套列表中的第二个最小数字

我必须使用递归返回python列表中的第二个最小数字,并且没有循环.我所做的是创建一个辅助函数,它返回列表中(最小,第二小)值的元组,然后我只需要使用tuple[1]我的second_smallest函数.

def s_smallest(L):

    if(len(L) == 2):
        if (L[0] >= L[1]):
            return (L[1],L[0])
        else:
            return (L[0],L[1])
    else:
        first_smallest,second_smallest = s_smallest(L[1:])

        if L[0] >= first_smallest and L[0] <= second_smallest:
            return (first_smallest, L[0])

        elif L[0] <= first_smallest:
            return (L[0], first_smallest)

        else:
            return (first_smallest, second_smallest)
Run Code Online (Sandbox Code Playgroud)

这有效,但现在我需要处理嵌套列表,所以s_smallest([1,2,[3,0]])应该返回(0,1).我试过这样做:

if isinstance(L[0],list):
    first_smallest,second_smallest = s_smallest(L[0])
else:
    first_smallest,second_smallest = s_smallest(L[1:])
Run Code Online (Sandbox Code Playgroud)

如果它是一个列表,获取第一个最小和第二个最小值,但我得到一个错误说builtins.TypeError: unorderable types: int() >= list().如何解决此问题以处理嵌套列表?

python algorithm recursion list

6
推荐指数
1
解决办法
790
查看次数

标签 统计

algorithm ×1

list ×1

python ×1

recursion ×1