Complete the code to check if the target is in the first row of the matrix.
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]] target = 3 if target in matrix[1]: print("Found") else: print("Not Found")
The first row of the matrix is accessed by matrix[0]. Checking if the target is in this row helps find it quickly.
Complete the code to find the row where the target could be by comparing the last element of each row.
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]] target = 13 row = 0 for i in range(len(matrix)): if matrix[i][-1] >= [1]: row = i break print(row)
We compare the last element of each row with the target to find the row where the target could be.
Fix the error in the binary search code to correctly find the target in the selected row.
def binary_search(row, target): left, right = 0, len(row) - 1 while left <= right: mid = (left + right) // 2 if row[mid] == [1]: return True elif row[mid] < target: left = mid + 1 else: right = mid - 1 return False
The binary search compares the middle element row[mid] with the target. So the condition should check if row[mid] == target.
Fill both blanks to complete the function that searches the target in the 2D matrix.
def search_matrix(matrix, target): for i in range(len(matrix)): if matrix[i][-1] >= target: return [1](matrix[i], target) return False def binary_search(row, target): left, right = 0, len(row) - 1 while left <= right: mid = (left + right) // 2 if row[mid] == target: return True elif row[mid] < target: left = mid + 1 else: right = mid - 1 return False print(search_matrix(matrix, 16))
The search_matrix function calls binary_search on the found row to check if the target exists. The row is matrix[i], passed as row.
Fill all three blanks to create a dictionary comprehension that maps each row index to True if the target is found in that row using binary search.
def binary_search(row, target): left, right = 0, len(row) - 1 while left <= right: mid = (left + right) // 2 if row[mid] == target: return True elif row[mid] < target: left = mid + 1 else: right = mid - 1 return False matrix = [[1, 3, 5], [7, 9, 11], [13, 15, 17]] target = 9 result = [1]: [2](matrix[i], target) for i in range(len(matrix)) if matrix[i][-1] >= target print(result)
The dictionary comprehension uses the row index i as key, calls binary_search on matrix[i] with the target, and stores True if found.
