前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >bisect 模块

bisect 模块

作者头像
超级大猪
发布2019-11-22 09:33:15
3830
发布2019-11-22 09:33:15
举报
文章被收录于专栏:大猪的笔记

对系统的bisect做了稍微的改造

代码语言:javascript
复制
"""Bisection algorithms."""


def insort(a, x, lo=0, hi=None, key=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.

    If x is already in a, insert it to the right of the rightmost x.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched. key (default None) defines an operation on the item before comparison.
    """
    if not key:
        def key(x): return x
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if key(x) < key(a[mid]):
            hi = mid
        else:
            lo = mid+1
    a.insert(lo, x)


def bisect_right(a, x, lo=0, hi=None, key=None):
    """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.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched. key (default None) defines an operation on the item before comparison.
    """
    if not key:
        def key(x): return x

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < key(a[mid]):
            hi = mid
        else:
            lo = mid+1
    return lo


def search(a, x, lo=0, hi=None, key=None):
    if not key:
        def key(x): return x
    index = bisect_right(a, x, lo, hi, key)
    if index == 0:
        return None
    else:
        searched = a[index-1]
        if key(searched) == x:
            return searched
        else:
            return None
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-10-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档