Binarysearch Problem Questions

Asked 2 years ago, Updated 2 years ago, 46 views

In an ordered two-dimensional list, you want to use binary search to create an algorithm that outputs true if desired, and false if not.

matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

def searchMatrix(matrix, target):

    matrix1 = sum(matrix, [])

    if len(matrix1) == 1 and target == matrix1[0]:
        return True

    if len(matrix1) == 1 and target != matrix1[0]: 
        return False

    if len(matrix1) == 0: 
        return False

    medium = len(matrix1) // 2 
    if target == matrix1[medium]:
        return True
    else:
        if target > matrix1[medium]: 
            return searchMatrix(matrix1[medium:], target) 
        else:
            return searchMatrix(matrix1[:medium], target)

The idea is to solve a two-dimensional list in one dimension and run a binary search from the list

can only concatenate list (not "int") to list

I can't solve it with this error.

Please tell me how to solve it.

python algorithm

2022-09-20 17:54

1 Answers

A two-dimensional list was inserted as the first input of the recursive function, but a one-dimensional list is being entered when recursive calls are made inside the recursive function.

The error is matrix1 = sum(matrix, []). For this code to work, matrix must be a two-dimensional list, but at first, there was no problem because it was two-dimensional, but the list changed to one-dimensional during the recursive call, and the changed one-dimensional list entered the sum function, resulting in an error.

Take the code of the sum function out.

And I think it's right to make matrix1[medium:]matrix1[medium+1:] in the third row from the bottom.

Please refer to the revised code below.


def searchMatrix(matrix1, target):
    if len(matrix1) == 1 and target == matrix1[0]:
        return True

    if len(matrix1) == 1 and target != matrix1[0]: 
        return False

    if len(matrix1) == 0: 
        return False

    medium = len(matrix1) // 2 
    if target == matrix1[medium]:
        return True
    else:
        if target > matrix1[medium]: 
            return searchMatrix(matrix1[medium + 1:], target) 
        else:
            return searchMatrix(matrix1[:medium], target)


matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]


new_matrix = sum(matrix, [])
print(searchMatrix(new_matrix,49))
print(searchMatrix(new_matrix,50))


2022-09-20 17:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.