Mahsa
Mahsa

Reputation: 97

The function doen't iterate over the whole array

I have the following code which gets two arrays and finds the location of each item in the second array based on the first array. For example, for 23 from loc1, which is between 20 and 25 in array it should return 20.

matrix_x = []
def binarySearch(alist, loc):
    for item in loc:
        midpoint = len(alist)//2
        if midpoint == 1:
            if item<alist[midpoint]:
                return matrix_x.append(alist[midpoint-1])
            else:
                return matrix_x.append(alist[midpoint])         
        else:
            if item<alist[midpoint]:
                return binarySearch(alist[:midpoint],loc)
            else:
                return binarySearch(alist[midpoint:],loc)
    return matrix_x

array = [5,10,15,20,25]
loc1= [23,7,11]

print(binarySearch(array, loc1))
print(matrix_x)

I expect to receive this array as the result:

[20,5,10]

But I receive only the first item like this:

[20]

Upvotes: 0

Views: 89

Answers (2)

Mike M&#252;ller
Mike M&#252;ller

Reputation: 85442

Just use the bisect module:

import bisect

def binarySearch(alist, loc):
    return [alist[bisect.bisect(alist, i) - 1] for i in loc]

array = [5,10,15,20,25]
loc1= [23,7,11]
print(binarySearch(array, loc1))

Output:

[20, 5, 10]

Finding the index is simpler:

def binarySearchIndex(alist, loc):
    return [bisect.bisect(alist, i) - 1 for i in loc]

Upvotes: 1

SuperStew
SuperStew

Reputation: 3054

You're returning the matrix_x.append statement, so it only ever appends 1 item, in this case 20. To get the behavior you want, you may need to restructure your function some.

Upvotes: 2

Related Questions