I'm attempting a binary search problem from leetcode and this is my code below (ignore if it's not the proper implementation, i'd like to figure it out myself):
class Solution:
def search(self, nums: List[int], target: int) -> int:
middle = int(len(nums)/2)
ind = -1
if(nums[middle] == target):
return ind
elif (nums[middle] > target):
ind = middle
nums = nums[:middle-1]
print(nums)
search(nums, target)
else:
ind = middle
nums = nums[middle:len(nums)-1]
print(nums)
search(nums, target)
I'm trying to get my code to recurse using a slice of a list, but I keep getting this error:
TypeError: unhashable type: 'list'
return _cache[type(pattern), pattern, flags]
Line 293 in _compile (/usr/lib/python3.10/re.py)
return _compile(pattern, flags).search(string)
Line 200 in search (/usr/lib/python3.10/re.py)
search(nums, target)
Line 17 in search (Solution.py)
ret = Solution().search(param_1, param_2)
Line 42 in _driver (Solution.py)
_driver()
Line 53 in <module> (Solution.py)
I don't understand what this means in regards to search(nums,targets).
Your code, somewhere, is doing from re import search
(or, shudders, from re import *
) at global scope. You then fail to properly invoke search
on self
, so it finds the re
module function and calls that instead. As a bonus error, you're not returning the values from your recursive calls, so any time you recurse you end up returning None
. The fixes are pretty simple at least, just change:
search(nums, target)
to:
return self.search(nums, target)
invoking the correct search
method on self
, and returning what it returns. The fix must be made in both places you're making the recursive call.