python 用递归寻找list中第二大的数字

python 用递归寻找list中第二大的数字
如题
second smallest: Return the second smallest number in a given list
These functions seem pretty trivial, and they are. But the trick here is that you need to implement all of
them recursively. You should also try to be efficient. In particular, no function should ever need to access
any element of the list more than once. (i.e, don’t go through the entire list once to find the max, and again
to find the min).
不能用到内置函数 只能用递归来做
搞了一晚上了想不出怎么做 多谢帮助!
罗昌平 1年前 已收到3个回答 举报

月亮上的桂花树 幼苗

共回答了24个问题采纳率:87.5% 举报

def second_smallest(elements, i):
if (i==1):
if elements[1]

1年前

2

elegantduke 幼苗

共回答了19个问题采纳率:84.2% 举报

基本思想是先找到最大的两个元素,而不只是次大元素

基础情况:长度为2列表的最大两个元素,长度为3列表的最大的两个元素

递归情况:长度为n的列表的最大的两个元素为前n-1项最大的两个元素与最后一个元素,这三个元素中最大的两个元素

def large2(l):
if len(l) == 2:
if l[0]>l[1]:
l[0],l[1]=l[1],l[0]
return l
elif len(l) == 3:
t = large2(l[0:-1])
if t[1]<=l[-1]:
return [t[1],l[2]]
else:
if t[0]>=l[2]:
return t
else:
return [l[2],t[1]]
else:
return large2(large2(l[0:-1])+[l[-1]])

l = [1,6,3,7,3,7,4,3,3,2,9,5]
print large2(l)[0]

题目真的不是那么简单,能满足一下我的好奇心么,这是什么学校的题目啊

1年前

1

zheng_shan 幼苗

共回答了21个问题采纳率:61.9% 举报

# helper recursion function
def min2_helper(a, start):
'''return the 1st and 2nd minimal in a[...

1年前

1
可能相似的问题
Copyright © 2024 YULUCN.COM - 雨露学习互助 - 19 q. 0.098 s. - webmaster@yulucn.com