Home > Net >  Why am I getting TypeError: list indices must be integers or slices and not the float value while fi
Why am I getting TypeError: list indices must be integers or slices and not the float value while fi

Time:01-14

I have two sorted arrays and I am trying to find median of two sorted arrays.For example,if input is nums1 = [1,3], nums2 = [2] then the output will median=2.00000 and if the input is p = [1,2], t = [3,4] then the output will be median=2.50000 I have added both the arrays together and sorted them and later by using their lengths I have tried to calculate the correct value. Below is my code

class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):

    nums1.extend(nums2)
    nums1.sort()

    if len(nums1)%2 ==0:
        a = len(nums1)/2
        return float(nums1[a] nums1[a-1])/float(2)
    else:
        a = len(nums1) / 2
        return float(nums1[a])

if __name__ == "__main__":
p = [1,3]
t = [2]
print(Solution().findMedianSortedArrays(p,t))

Below is the error in the logs.

 return float(nums1[a])
TypeError: list indices must be integers or slices, not float

CodePudding user response:

Because

Division of integers yields a float

but you could trivially check this by printing out a just before using it as an index. And the error is extremely clear that a is a float at that point.

Either coerce it to int, as

nums1[int(a)]

or use floor division, with

a = len(nums1) // 2

CodePudding user response:

In python a division always returns a float, you cannot use a float for indexing lists or other iterables, convert it to an int first.

a = [1, 2, 3]

a[1/1]  # TypeError: list indices must be integers or slices, not float

a[int(1/1)]  # OK

NB. int conversion rounds down int(2.5) is 2

  • Related