为了账号安全,请及时绑定邮箱和手机立即绑定

使用递归选择列表中的最小值

使用递归选择列表中的最小值

HUX布斯 2021-08-14 16:28:46
这是我为了使用递归查找列表中的最小值而定义的一个函数。但是,我在其内部调用了该函数两次,我认为这有点奇怪。有没有办法绕过这个功能append()?我们还没有研究它,所以我问是否有一种更简单的方法可以通过不使用来获得相同的解决方案append()?def minimum(lst):    """    parameters : lst of type list    return : the value of the smallest element in the lst    """    if len(lst) == 1:        return lst[0]    if lst[0] < lst[1]:        lst.append(lst[0])        return(minimum(lst[1:]))    return(minimum(lst[1:])) 
查看完整描述

3 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

使用额外的变量?


def minimum(lst, current_min=None):

    if not lst:

        return current_min

    if current_min is None:

        current_min = lst[0]

    elif lst[0] < current_min:

        current_min = lst[0]

    return minimum(lst[1:], current_min)


查看完整回答
反对 回复 2021-08-14
?
弑天下

TA贡献1818条经验 获得超8个赞

这是一个非常明确的版本,由于注释和变量名称,它应该易于阅读。


def minimum(lst):

    # base case

    if len(lst) == 1:

        return lst[0]


    # get first element and minimum of remaining list

    first = lst[0]

    rest = lst[1:]

    min_of_rest = minimum(rest)


    # return the smaller one of those two values

    if first < min_of_rest:

        return first

    else:

        return min_of_rest



查看完整回答
反对 回复 2021-08-14
  • 3 回答
  • 0 关注
  • 168 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号