1

Hi I'm trying to write a recursive binary search but I'm getting an NameError. My code is as follows:

This is for a self development project im working on in python.

    def search(self, list, list_start, list_end, search_for):
        if list_end >= list_start:

            mid_point = int(list_start + (list_end - list_start) / 2)

            if list[mid_point] == search_for:
                return mid_point

            elif list[mid_point] > search_for:
                return search(list, list_start, mid_point-1, search_for)

            else:
                return search(list, mid_point+1, list_end, search_for)

        else:
            return -1

binaryS = BinarySearchModel()
list = [22, 2, 1, 24, 3, 43, 10, 40, 0, 48, 34, 19, 5, 3, 45]
x = 24
sorted_list = binaryS.sort_arr(list)
print('Print sorted list {}'.format(sorted_list))
result = binaryS.search(sorted_list, 0, len(sorted_list)-1, x)

on the second recursive call is where I'm getting the error:

Traceback (most recent call last):
  File "binary_search_model.py", line 29, in <module>
    result = binaryS.search(sorted_list, 0, len(sorted_list)-1, x)
  File "binary_search_model.py", line 19, in search
    return search(list, mid_point+1, list_end, search_for)
NameError: name 'search' is not defined
user2152012
  • 161
  • 1
  • 4
  • 17
  • `search` is not defined, assuming this is part of a class definition (always provide a [mcve]). You have to use `self.search`, or better yet, move it out of a pointless class and just use a function. – juanpa.arrivillaga Apr 10 '19 at 17:15

2 Answers2

2

It looks like your search function is inside a class. You need to call your search function using self.search(self, list, list_start, list_end, search_for)

1

If you are calling a method that is part of a class from within that class you need to use self

self.search(arguments)

In this case self is binaryS

Cailan
  • 86
  • 3