正整数列表,N个正整数,请用递归求解最大数
1.求数组中的最大数
2.1+2+3+...+n
3.求n个整数的积
def getMax(l):
if len(l) == 1:
return l[0]
else:
return l[0] if l[0] > getMax(l[1:]) else getMax(l[1:])
s = getMax([4, 2, 33, 7, 8, 9])
print(s)
'''--result
33
'''
def getSum(l):
if len(l) == 1:
return l[0]
else:
return l[0] + getSum(l[1:])
print(getSum([4, 2, 33, 7, 8, 9]))
def getMul(l):
if len(l) == 1:
return l[0]
else:
return l[0] * getMul(l[1:])
print(getMul([4, 2, 33, 7, 8, 9]))
def max(inlist:list,maxnumber = 0):
if len(inlist) == 0:
return maxnumber
else:
_=inlist.pop(0)
if _<maxnumber:
return max(inlist,maxnumber)
else:
return max(inlist,_)
def sum(inlist:list):
if len(inlist) == 1:
return inlist[0]
else:
return inlist.pop(0)+sum(inlist)
def avg(inlist:list):
if len(inlist) == 1:
return inlist[0]
else:
return inlist.pop(0)*avg(inlist)
a=[1,5,2,4,6,9,33,2,0,1,5,8]
print(max(a))
a=[1,5,2,4,6,9,33,2,0,1,5,8]
print(sum(a))
a=[1,5,2,4,6,9,33,2,2,1,5,8]
print(avg(a))
def get_max(lst, index, max):
if index < len(lst):
if lst[index] > max:
max = lst[index]
max = get_max(lst, index + 1, max)
return max
else:
return max
def get_sum(lst, index, sum):
if index < len(lst):
sum += lst[index]
return get_sum(lst, index + 1, sum)
else:
return sum
def get_product(lst, index, product):
if index < len(lst):
product *= lst[index]
return get_product(lst, index + 1, product)
else:
return product
if __name__ == "__main__":
print(f'数组中的最大数:{get_max([3,4,5,6,7,2,1,7,8,5,9,2,34,56,32,33,53,43,32],0,0)}')
print(f'n个整数的和:{get_sum([1,2,3,4],0,0)}')
print(f'n个整数的积:{get_product([1,2,3,4],0,1)}')