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

时间:2018-11-10 21:52:11

标签: python list recursion

这是我定义的函数,目的是使用递归在列表中找到最小值。但是,我在自身内部两次调用了该函数,我认为这有点奇怪。 函数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:])) 

6 个答案:

答案 0 :(得分:3)

我想您可以这样做以避免附加:

select teamid, 
       playerid, 
       dbo.FullName(playerid) as fullName, 
       Total_Hits, 
       Total_At_Bats, 
       Totals_At_Bats, 
       Batting_Avg, 
       Team_Batting_Rank, 
       All_Batting_Rank 
FROM batting

但我认为只用一次调用最小值即可更好:

a.playerid

答案 1 :(得分:2)

使用其他变量吗?

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)

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

在Python 3中,我很想尝试:

def minimum(lst):
    if not lst:
        return None

    a, *rest = lst

    if rest:
        b = minimum(rest)

        if b < a:
            return b

    return a

除@ roeen30(+1)以外,但包括当前接受的大多数解决方案,都不会针对minimum([])进行辩护。结果很多人进入了无限递归!

答案 4 :(得分:-1)

您可以使用以下程序:

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]
    temp_min = minimum(lst[1:])
    if lst[0] < temp_min:
        return lst[0]
    else:
        return temp_min

答案 5 :(得分:-1)

如果您的任务只是在列表中找到具有给定长度的最小值,那么我不完全知道为什么要使用递归。有更有效的方法可以做到这一点,例如Python的内置函数。例如:

std::vector

这将打印出1。