【问题标题】:How to find multiple values using Binary Search in Python如何在 Python 中使用二分搜索查找多个值
【发布时间】:2018-11-14 09:03:28
【问题描述】:

我正在使用标准的二进制搜索算法,该算法将整数值作为参数,并在列表中搜索整数。但是,我希望能够找到列表中与搜索值匹配的每个整数的位置索引。到目前为止我所拥有的是:

def bin_search(x):
    my_list = [57,68,76,77,82,86,89,89,89,98,100]
    bottom = 0
    top = len(my_list)-1
    found = False
    location = -1
    while(bottom <= top) and not(found):
        middle = int((bottom + top)//2)
        if(my_list[middle] == x):
            location = middle
            found = True
        else:
            if x < my_list[middle]:
                top = middle - 1
            else:
                bottom = middle + 1

    return location

print(bin_search(89))

任何有助于使这个二分搜索能够找到两个值的帮助将不胜感激!

【问题讨论】:

  • 发布堆栈跟踪。 在哪里你得到错误?
  • 你为什么要列出location?我敢打赌这是你错误的根源。
  • 你需要重新发明轮子吗? The bisect module 提供的 API 可以直接确定给定值的 the leftright 边界(或者您直接向左并开始线性扫描,直到到达相同值的运行结束)。
  • 我把它做成了一个列表,这样我就可以为这个位置存储多个值。
  • @Newoej bisect 二分查找。见the docs。 (并且,当您使用它时,请注意文档链接到源代码,因此如果您不确定他们是如何完成某些特定功能的,您只需单击并查看他们是如何做到的。)

标签: python binary-search


【解决方案1】:

在二进制搜索的末尾添加此代码将为用户提供正在搜索的值的第一次和最后一次出现的索引(在本例中为 x)。然后,用户可以使用索引来查找与搜索项匹配的索引范围,因为他们知道搜索项的第一次和最后一次出现的索引。

# Index of last occurrence
location2 = -1
# Index of first occurrence
location3 = -1

# Finds last index that matches x
for I in range(len(my_list)):
    if my_list[I] == x:
        location2 = I
# Finds first index that matches x
for I in range(len(my_list)):
    if my_list[I] == x:
        location3 = I
        break

【讨论】:

    【解决方案2】:

    想到的是执行两次二进制搜索:一次在列表中以排序顺序,另一次在列表中以相反顺序排序。

    然后知道列表的长度,您可以获取您要查找的元素的第一个和最后一个索引。

    来自article

    二分查找的一个缺点是,如果数组中某个元素多次出现,它不会返回第一个元素的索引,而是返回最靠近中间的元素的索引

    你可以做的是remove duplicates from the list and remember the index,然后进行二分查找。

    【讨论】:

      【解决方案3】:

      这可以很容易地在 python 中完成, 通过检查要定位的第一个匹配项并在匹配时从列表中删除该值。 并继续搜索...

      print("Binary Search!")
      my_arr =[0, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10]
      my_arr.append(4)
      print(my_arr)
      target = 4
      low = 0
      high = len(my_arr)-1
      while(low<=high):
          mid = (low+high)//2
          if my_arr[mid]==target:
              print("found target",my_arr[mid],mid)
              my_arr.remove(my_arr[mid])
          elif my_arr[mid]>target:
              high =mid-1
          else:
              low = mid +1
      

      【讨论】:

        【解决方案4】:

        下面的代码是一个具有恒定运行时间的二进制搜索算法。该函数利用while 循环遍历列表中的变量或值列表,并在达到条件时退出,但在未找到目标时停止运行并返回None 值。

        def binarySerach(list, target):
            first = 0
            last = len(list) -1  #get size of list
            
            while first <= last:
                midpoint = (first + last) // 2 # rounds to whole number
                if list[midpoint] == target:
                    return midpoint
                elif list[midpoint] < target:
                    first = midpoint + 1
                else:
                    last = midpoint - 1 
           return None
        
        def verify(index):
            if index is not None:
                print("Target found at index: ", index)
            else:
                print("Target not found in list")
            
        
        my_list = [57,68,76,77,82,86,89,89,89,98,100]
        result = binarySerach(my_list,89)
        verify(result)
        

        【讨论】:

          猜你喜欢
          • 2012-08-22
          • 1970-01-01
          • 1970-01-01
          • 2020-04-06
          • 2022-08-22
          • 2013-11-18
          • 2014-03-02
          • 2021-01-28
          • 2015-10-09
          相关资源
          最近更新 更多