Getting error in maxium number as - TypeError: list indices must be integers or slices, not float

Viewed 51

New to python, in this code when compiling gives me the error as:

Traceback (most recent call last):   File "main.py", line 5, in maximum
lmax = maximum(A,l,(l+r)/2)   File "main.py", line 5, in maximum
lmax = maximum(A,l,(l+r)/2)   File "main.py", line 5, in maximum
lmax = maximum(A,l,(l+r)/2)   [Previous line repeated 52 more times]   File "main.py", line 3, in maximum
return A[r] TypeError: list indices must be integers or slices, not float

Here is the Code:

def maximum(A,l,r):
  if(r-l == 0):
    return A[r]

  lmax = maximum(A,l,(l+r)/2)
  rmax = maximum(A,(l+r/2)+1,r)
  print(lmax,rmax)
  if(rmax<lmax):
    return lmax
  else:
    return rmax

A = [9,12,15,5,2]
maximum(A,1,5)

This is the algorithm i took to convert to code: enter image description here

2 Answers

The error is obvious that the index of a list can not be float.

(l+r)/2 and r/2 use true division /, and in true division the result of dividing two integers is a float.

so replace / with floor division //.

see this ref.

And to avoid recursion, we need a condition to return from the maximum function.

At one point you make r=1.0 (float because of the division) by calling maximum function inside maximum function. When you call maximum funtion with r = 1.0 and l =1, difference is now 0.0 and r = 1.0 float and then you try to access list as A[1.0] which throws an error.

Related