[LeetCode]TypeError: ‘Solution’ object is not subscriptable, how to deal with it? [closed]

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 a self parameter to the method as the first parameter.

    – 

  • 1

    Since your search is a method of the Solution class (and not a static method), the first argument it receives is self, which refers to the object whose method is being called. In your code, you call this num_list. Since num_list is an object of the Solution class, it can’t be subscripted. As you’ve found out, type hints do not enforce types — they are just hints

    – 




  • 1

    The code shown will raise an IndentationError exception

    – 

  • 2

    Please make sure you copy-paste the correct minimal reproducible example.

    – 

  • 1

    Where is two_divide_recursive defined? Why recursion?

    – 




Leave a Comment