Question

I just posted a question about this code, and I am sorry to do it again, but my return statement is not working. Whenever I try to run the code, it asks for a global variable of position, which I am trying to return in the searching method. Any help is appreciated. Thanks.

def main():

    names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter','Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']

    binarySearch(names, "Ava Fischer")

    print("That name is at position "+str(position))


def binarySearch(array, searchedValue):

    begin = 0 
    end = len(array) - 1 
    position = -1 
    found = False

    while not found and begin<=end:
        middle=(begin+end)//2

        if array[middle] == searchedValue:
            found=True 
            position = middle
        elif array[middle] >searchedValue:
            end = middle-1
        else:
            first = middle+1

    return position
Était-ce utile?

La solution

At the moment you are calling your function, but just throwing the result away. You don't actually give a value from your function call (you use return just fine):

You want something like:

position = binarySearch(names, "Ava Fischer")

The variable that you are expecting to exist globally is local to the scope of binarySearch. We can get it by assigning a variable to the returned value, like above.

Autres conseils

This is a scope issue. In the function binarySearch you are declaring a local variable position, so it is only accessible within that function. Since that function will return a value, you can assign that result to a variable:

position = binarySearch(names, "Ava Fischer")
print("That name is at position " + str(position))
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top