i was writing a reccursive solution to find the maximum element but i am getting a typeError at last return function in the code , can anyone tell me why?
def max(arr,i,size,max,index):
if(i == len(arr) - 1):
return index
elif(arr[i] > max):
return max(arr,i 1,arr[i],i)
return max(arr,i 1,max,index)
if __name__ == "__main__":
arr = [2,1,3,9]
print(max(arr,0,len(arr) - 1,arr[0],0))
CodePudding user response:
You had a lot of bugs in your code
the name of your function was
maxand it also received an argument namedmaxwhich caused the problem since when you try to call your function recursively your code thought you are "calling the argument" which is impossible since it's an int (by the way max isn't a good name since it is already used by python )you sent an argument
sizeto the function but never used it so I removed itwhen your recursion got to the end of the array it returned the index (of the end of the array i.e the size) instead of returning the
max_valyour recursion stopped when it got to
len(arr)-1instead oflen(arr)thus ignoring the last cell of thearrThis should do the trick :def max(arr,i,max_val,index): if(i == len(arr)): return max_val elif(arr[i] > max_val): return max(arr,i 1,arr[i],i) return max(arr,i 1,max_val,index)
