Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 二进制搜索卡在infinte循环中_Python_Binary Search - Fatal编程技术网

Python 二进制搜索卡在infinte循环中

Python 二进制搜索卡在infinte循环中,python,binary-search,Python,Binary Search,我的二进制搜索似乎陷入了一个无限循环,因为它没有为我的测试数据输出任何东西。第二个列表按排序,我检查第一个列表中的重复项,然后将这些重复项添加到空列表中。我的二进制搜索算法一直执行到剩下一个元素,然后我检查这个元素是否与该项相同,我希望保留这个结构。我相信问题是,正确的指针没有减少,但我不明白为什么会这样 def detect_duplicates_binary(第一个_列表,第二个_列表): 重复项列表=[] 对于第一个列表中的项目: 左=0 右=len(第二个列表)-1 当左项: 右=中点-

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

def detect_duplicates_binary(第一个_列表,第二个_列表):
重复项列表=[]
对于第一个列表中的项目:
左=0
右=len(第二个列表)-1
当左<右:
中点=(左+右)//2
如果第二个列表[中点]>项:
右=中点-1
其他:
左=中点
如果(第二个_列表[左]==项):
重复项\u列表。追加(项)
返回重复项列表
病理学 下面是一个可能导致无限循环的执行序列:

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

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

你可能想用a来做这件事,或者看看你可以打印左、右、中点和其他你想看到的,然后你会找到答案
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
right = len(second_list)