import random,operator
def getMax(arr,l,r):
if l == r:
return arr[l]
#决定了递归函数的返回类型
n = len(arr)
mid = (l+r)//2
left = getMax(arr,l,mid)
right = getMax(arr,mid+1,r)
return max(left,right)
#for test
def generateRandomArray(size,value):
arr = []
for i in range(size):
arr.append(int((value+1)*random.random())-int(value*random.random()))
return arr
def right_mothod(arr):
a = max(arr)
return a
def is_right(times,size,value,func):
succeed = True
for i in range(times):
arr1 = generateRandomArray(size,value)
arr2 = arr1.copy()
arr3 = arr1.copy()
g = getMax(arr1,0,len(arr1)-1)
r = func(arr2)
if not operator.eq(g,r):
succeed = False
print(arr3)
break
print('nice' if succeed==True else 'wrong')
if __name__ == '__main__':
is_right(500,6,10,right_mothod)
递归求数组最大值
最新推荐文章于 2024-03-17 08:45:43 发布