简体   繁体   English

该函数不会遍历整个数组

[英]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. 例如,对于loc1中的23(在数组loc1于20和25之间),应返回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]

You're returning the matrix_x.append statement, so it only ever appends 1 item, in this case 20 . 您将返回matrix_x.append语句,因此它只会追加1个项目,在本例中为20 To get the behavior you want, you may need to restructure your function some. 为了获得所需的行为,您可能需要对函数进行一些重组。

Just use the bisect module : 只需使用bisect模块

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM