2 years ago

#56181

test-img

sourabh tantuway

Same program giving error for Python3 but not for Python on leetCode

For the leetCode problem "74.Search a 2D Matrix" the following program is accepted for Python.

class Solution(object):
    def searchMatrix(self, matrix, target):
        rows = len(matrix) 
        cols = len(matrix[0])
        
        low, high = 0, rows*cols -1
        
        while low <= high:
            mid = (low + high) /2 
            num = matrix[mid//cols][mid%cols]
            
            if num == target:
                return True
            elif num < target:
                low = mid+1
            else:
                high = mid-1
                
        return False

The same program is giving error for Python3 as:

TypeError: list indices must be integers or slices, not float
    num = matrix[mid//cols][mid%cols]
Line 10 in searchMatrix (Solution.py)
    ret = Solution().searchMatrix(param_1, param_2)
Line 45 in _driver (Solution.py)
    _driver()
Line 56 in <module> (Solution.py)

Please help me to know why it is giving the error. "mid//cols" must be returning int value, not float.

python

python-3.10

0 Answers

Your Answer

Accepted video resources