I submitted a code segment on leetcode,there is the link of my question below,
https://leetcode.com/problems/binary-search/
Firstly, I used while() loop to complete this question and succeeded, but when I transform it to recursion, I ran into a bug as below.
TypeError: search() takes from 2 to 3 positional arguments but 5 were given
return search(self,num_list, target, middle + 1, right)
Line 13 in search (Solution.py)
ret = Solution().search(param_1, param_2)
Line 39 in _driver (Solution.py)
_driver()
Line 50 in <module> (Solution.py)
This is my code segment:
class Solution:
def search(self,num_list: list[int], target: int, left: int = 0, right: int = 5) -> int:
if left > right:
return -1
middle = (left + right) // 2 # 2
if num_list[middle] == target:
return middle
elif num_list[middle] > target:
return search(self,num_list, target, left, middle - 1)
elif num_list[middle] < target:
return search(self,num_list, target, middle + 1, right)
It means the key is the argument of search(),but i don’t know how to fix it.
The first argument to a method is the object itself (typically called
self
). You need to add aself
parameter to the method as the first parameter.Since your
search
is a method of theSolution
class (and not a static method), the first argument it receives isself
, which refers to the object whose method is being called. In your code, you call thisnum_list
. Sincenum_list
is an object of theSolution
class, it can’t be subscripted. As you’ve found out, type hints do not enforce types — they are just hintsThe code shown will raise an IndentationError exception
Please make sure you copy-paste the correct minimal reproducible example.
Where is two_divide_recursive defined? Why recursion?
Show 3 more comments