I am getting TypeError: 'int' object is not callable for the reccursive solution

Question:

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))
Asked By: Karthik PM

||

Answers:

You had a lot of bugs in your code

  1. the name of your function was max and it also received an argument named max which 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 )

  2. you sent an argument size to the function but never used it so I removed it

  3. when 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_val

  4. your recursion stopped when it got to len(arr)-1 instead of len(arr) thus ignoring the last cell of the arr
    This 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)
    
Answered By: Ohad Sharet
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.