Home > Software engineering >  Type Error in python recursive binary search problem
Type Error in python recursive binary search problem

Time:11-04

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left, right = 0, len(nums) - 1
        
        while left <= right:
            curr_ind = (right left)//2
            print(nums[curr_ind   1:len(nums)])
            if nums[curr_ind] == target:
                return curr_ind
            elif nums[curr_ind] > target:
                return search(nums[left:curr_ind], target)
            elif nums[curr_ind] < target:
                return search(nums[curr_ind   1:len(nums)], target)
            
        return -1

I am getting Unhashable Type 'list' error in the second to last line. I don't think I am using dictionary in this problem, but I am not sure why it is giving me this error.

CodePudding user response:

I think you are using recursion wrongly, try this:

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left, right = 0, len(nums) - 1
        
        while left <= right:
            curr_ind = (right left)//2
            print(nums[curr_ind   1:len(nums)])
            if nums[curr_ind] == target:
                return curr_ind
            elif nums[curr_ind] > target:
                right = curr_ind - 1
            elif nums[curr_ind] < target:
                left = curr_ind   1
            
        return -1
  • Related