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



这是我定义的一个函数,目的是使用递归查找列表中的最小值。然而,我在函数内部调用了两次,我觉得这有点奇怪。有办法绕过函数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:])) 

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

def minimum(lst):
if len(lst)==1:
return lst[0]
if lst[0] < lst[1]:
return minimum(lst[0:1]+ lst[2:])
else:
return minimum(lst[1:])

但我认为这个更好,只需要一个最低限度的调用:

def minimum(lst):        
if len(lst) == 1:
return lst[0]        
s = minimum(lst[1:])
return s if s < lst[0] else lst[0]

是否使用其他变量?

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)

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

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

在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([])进行辩护。许多人因此进入无限递归!

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

list_of_ints = [4,2,7,6,8,1,5,9,2]
print(min(list_of_ints)

这将打印出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

最新更新