使用递归求最大值
def max_num(lists):
if len(lists) == 1:
return lists[0]
elif lists[0] > max_num(lists[1:]):
return lists[0]
else:
return max_num(lists[1:])
print(max_num([5, 3, 4, 2]))
使用递归求最小值
def min_num(lists):
if len(lists) == 1:
return lists[0]
elif lists[0] < min_num(lists[1:]):
return lists[0]
else:
return min_num(lists[1:])
print(min_num([5, 3, 4, 2]))
使用递归求最大值和最小值
def maxMin(L,start,end):
if end-start <=2:
return (max(L[start],L[end]),min(L[start],L[end]))
max1,min1 = maxMin(L,start,(start+end)//2)
max2,min2 = maxMin(L,(start+end)//2+1,end)
return (max(max1,max2),min(min1,min2))
list_ = [11,22,43,-10,33,28,90]
print(maxMin(list_,0,len(list_)-1))