zoukankan      html  css  js  c++  java
  • bisect in Python

    Binary Search 是一种用于搜索排序列表中元素的technique。在本文中,我们将研究执行Binary Search 的库函数。

    Finding first occurrence of an element.

    bisect.bisect_left(a, x, lo=0, hi=len(a)) : Returns leftmost insertion point of x in a sorted list. Last two parameters are optional, they are used to search in sublist.

    # 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) 

    Output:

    First occurrence of 4 is present at 2

    Finding greatest value smaller than 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) 

    Output:

    Largest value smaller than 7 is at index 3

    Finding rightmost occurrence

    bisect.bisect_right(a, x, lo=0, hi=len(a)) Returns rightmost insertion point of x in a sorted list a. Last two parameters are optional, they are used to search in sublist.

    # 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) 

    Output:

    Last occurrence of 4 is present at 3

     
  • 相关阅读:
    CH1301 邻值查找【set应用】
    poj1185 炮兵阵地【状压DP】
    codeforces#516 Div2---ABCD
    2017ACM-ICPC沈阳区域赛
    poj2411 Mondriaan's Dream【状压DP】
    hdu2196 Computer【树形DP】【换根法】
    poj3345 Bribing FIPA【树形DP】【背包】
    poj1463 Strategic game【树形DP】
    poj1191 棋盘分割【区间DP】【记忆化搜索】
    CH5E09 能量相连【区间DP】
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13795082.html
Copyright © 2011-2022 走看看