0

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]
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Mahsa
  • 97
  • 1
  • 7
  • remove the `return` keyword by using the return statement you end the script execution. – Amr Aly Jan 30 '18 at 23:19
  • 1
    Your algorithm is questionable as it combined two very different features into a single function; my recommendation is to decouple the two, first being the recursive `binarySearch` into its own thing that takes the list and __one__ location, the other being the iteration through the list of locations and passing that to the decoupled `binarySearch` function. – metatoaster Jan 30 '18 at 23:20

2 Answers2

2

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.

SuperStew
  • 2,857
  • 2
  • 15
  • 27
1

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]
Mike Müller
  • 82,630
  • 20
  • 166
  • 161