python - python 二分搜索陷入无限循环

标签 python binary-search

我的二分搜索似乎陷入了无限循环,因为它没有为我的测试数据输出任何内容。 Second_list 按排序顺序排列,我检查第一个列表中的重复项,然后将这些重复项添加到空列表中。我的二分搜索算法执行,直到剩下一个元素,然后我检查该元素是否与该项目相同,并且我想保留此结构。我相信问题是右指针没有减少,但我不明白为什么会这样。

def detect_duplicates_binary(first_list, second_list):

    duplicates_list = []

    for item in first_list:

        left = 0
        right = len(second_list) - 1

        while left < right:

            midpoint = (left + right) // 2

            if second_list[midpoint] > item:
                right = midpoint - 1
            else:
                left = midpoint

        if (second_list[left] == item):
            duplicates_list.append(item)

    return duplicates_list

最佳答案

病理学

以下是可能导致无限循环的执行顺序:

>>> left = 10
>>> right = 11
>>> left < right
True
>>> midpoint = (left + right) // 2
>>> midpoint
10
>>> left = midpoint
>>> left
10
>>> # No change!

建议 1

仅分解出二等分函数,并将其与“检测重复”代码分开进行测试,“检测重复”代码是一个单独的算法。

建议2

使用Python自己的bisect模块——它已经过测试和记录。

这是其代码的简化版本:

def bisect_right(a, x):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e <= x, and all e in
    a[i:] have e > x.  So if x already appears in the list, a.insert(x) will
    insert just after the rightmost x already there.
    """
    lo = 0
    hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < a[mid]: hi = mid
        else: lo = mid+1
    return lo

建议3

将右侧索引增加 1:

right = len(second_list)

希望这对您有所帮助。祝你好运:-)

关于python - python 二分搜索陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57619080/

相关文章:

algorithm - 对二维数组进行二分搜索以找到局部最大值?这个算法有什么问题?

php - 接口(interface)只是 "Syntactic Sugar"吗?

python - 不同位置的 mktime 问题

go - 高效二分查找 []byte 而不是 [][]byte

c++ - 从数组中查找 MIN MAX 对

c# - 日期 <= n 的最大日期的二进制搜索日期列表

java - 文件必须位于何处才能对其使用算法(即二进制搜索)?

python - python中的LDA使用sklearn

python - 如何在Python中解码这种奇怪的编码?

python - scipy.integrate.odeint 是否可以输出内部计算