📜  Python分搜索(平分)

📅  最后修改于: 2021-09-16 11:04:34             🧑  作者: Mango

二分搜索是一种用于在排序列表中搜索元素的技术。在本文中,我们将着眼于进行二分搜索的库函数。

查找元素的第一次出现。

# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
  
def BinarySearch(a, x):
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    else:
        return -1
  
a  = [1, 2, 4, 4, 8]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
    print(x, "is absent")
else:
    print("First occurrence of", x, "is present at", res)
输出:
First occurrence of 4 is present at 2

寻找小于 x 的最大值。

# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
  
def BinarySearch(a, x):
    i = bisect_left(a, x)
    if i:
        return (i-1)
    else:
        return -1
  
# Driver code
a  = [1, 2, 4, 4, 8]
x = int(7)
res = BinarySearch(a, x)
if res == -1:
    print("No value smaller than ", x)
else:
    print("Largest value smaller than ", x, " is at index ", res)
输出:
Largest value smaller than  7  is at index  3

寻找最右边的出现

# Python code to demonstrate working
# of binary search in library
from bisect import bisect_right
  
def BinarySearch(a, x):
    i = bisect_right(a, x)
    if i != len(a)+1 and a[i-1] == x:
        return (i-1)
    else:
        return -1
  
a  = [1, 2, 4, 4]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
    print(x, "is absent")
else:
    print("Last occurrence of", x, "is present at", res)
输出:
Last occurrence of 4 is present at 3

请参考 Binary Search 来编写您自己的 Binary Search 代码。

参考 :
https://文档。Python.org/3/library/bisect.html

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程