'Python throws a 'not defined' error at a declared function

I wrote the following code. The function that I am calling is declared at the top:

class Solution:
    
    def search_val(self, arr, low, high, x):
        
        high = len(arr)
        low = 0
        
        if high >= low:
            
            mid = (high + low) // 2
            
            if arr[mid] == x:
                print('Target is in the middle', mid)
            
            elif arr[mid] > x:
                print(search_val(self, arr, low, mid - 1, x))
            
            else:
                print(search_val(self, arr, mid + 1, high, x))
        
        else:
            print('-1')

    def searchInsert(self, nums: List[int], target: int) -> int:
        
        high = len(nums)
        low = 0
        
        print(self.search_val(nums, low, high, target))

But I am getting this error:

NameError: name 'search_val' is not defined
    print(search_val(nums, low, high, target))
Line 29 in searchInsert (Solution.py)
    ret = Solution().searchInsert(param_1, param_2)
Line 54 in _driver (Solution.py)
    _driver()
Line 65 in <module> (Solution.py)

Where am I going wrong?



Solution 1:[1]

search_val is not a global function. It is a member of the class, even though it's not using self.

If you need to have this as a member of the class, then you need to change the header to:

    def search_val(self, arr, low, high, x):

and you need to call it as:

        print(self.search_val(nums, low, high, target))`

If this is for a contest, they usually want you to RETURN the value, rather than PRINT the value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Roberts