bisect模块

bisect是Python提供的二分查找模块

源码如下:

"""Bisection algorithms."""

def insort_right(a, x, lo=0, hi=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.
""" 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 < a[mid]: hi = mid
else: lo = mid+1
a.insert(lo, x) def bisect_right(a, x, lo=0, hi=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.
""" 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 < a[mid]: hi = mid
else: lo = mid+1
return lo def insort_left(a, x, lo=0, hi=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 left of the leftmost x. Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
""" 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 a[mid] < x: lo = mid+1
else: hi = mid
a.insert(lo, x) def bisect_left(a, x, lo=0, hi=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 before the leftmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
""" 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 a[mid] < x: lo = mid+1
else: hi = mid
return lo # Overwrite above definitions with a fast C implementation
try:
from _bisect import *
except ImportError:
pass # Create aliases
bisect = bisect_right
insort = insort_right

我们可以看到,bisect模块中一共只有4个函数:

insort_right(a, x, lo=0, hi=None)
insort_left(a, x, lo=0, hi=None)
bisect_right(a, x, lo=0, hi=None)
bisect_left(a, x, lo=0, hi=None)

他们的区别是,insort要执行插入操作,而bisect不执行插入操作,只找到该插入的index。left和right的区别是,如果列表中已经存在该值,left表示插在其左边,right表示插在其右边。

参数:

a:列表
x:要插入的数
lo:列表开始索引,默认为0
hi:列表结束索引,默认为len(a)

源码在最后提供了两个函数别名:

# Create aliases
bisect = bisect_right
insort = insort_right

bisect默认是bisect_right,insort默认是insort_right。

[Python之路] bisect模块的更多相关文章

  1. python笔记之bisect模块

    python笔记之bisect模块 当你决定使用二分搜索时,这个模块会给你带来很大的帮助. 例子 import bisect L = [1,3,3,6,8,12,15] x = 3 #在L中查找x,x ...

  2. python之路:模块初识

    python王者开发之路:模块初识 模块初识我现在讲的确有点早.不过没关系,后面我会详细说模块. 模块,也就是库,是python三剑客之一.这三剑客,函数.库和类,都是由程序编写而成的.之所以我先说模 ...

  3. Python之路-numpy模块

    这里是首先需要安装好Anaconda Anaconda的安装参考Python之路-初识python及环境搭建并测试 配置好环境之后开始使用Jupyter Notebook 1.打开cmd,输入 jup ...

  4. python之路——常用模块

    阅读目录 认识模块 什么是模块 模块的导入和使用 常用模块一 collections模块 时间模块 random模块 os模块 sys模块 序列化模块 re模块 常用模块二 hashlib模块 con ...

  5. python标准库 bisect模块

    # -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #bisect #作用:维护有序列表,而不必在每次向列表增加一个元素 ...

  6. 小白的Python之路 day1 模块初识

    模块初识 Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有相应的Python库支持,以后的课程中会深入讲解常用到的各种库,现在,我们先来象征性的学2个简单的. ...

  7. 小白的Python之路 day5 模块XML特点和用法

    模块XML的特点和用法 一.简介 xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今 ...

  8. 小白学习Python之路---re模块学习和挑战练习

    本节大纲: 1.正则表达式 2.re模块的学习 3.速记理解技巧 4.挑战练习--开发一个简单的python计算器 5.心得总结 6.学习建议 正则表达式: 正则表达式,又称规则表达式.(英语:Reg ...

  9. python之路----logging模块

    函数式简单配置 import logging logging.debug('debug message') #bug logging.info('info message') #信息 logging. ...

随机推荐

  1. Java&Eclipse&Maven的折腾

    趁着寒假对于Java的余热,继续了对Java的征途.这次并没有太多琐碎的事情打断我的学习,于是借着这股热情去图书馆借了两本国外的书(中译版),对于程序的爱好一定要坚持下来,才开通了这个博客以坚持学习.

  2. Python学习,第四课 - 字符串相关操作

    这次主要说说Python中字符串的使用方法详解 capitalize 首字母大写 print('chengshou'.capitalize()) #输出结果:Chengshou title 修改成标题 ...

  3. redis缓存数据库及Python操作redis

    缓存数据库介绍  NoSQL(NoSQL = Not Only SQL ),意即“不仅仅是SQL”,泛指非关系型的数据库,随着互联网web2.0网站的兴起,传统的关系数据库在应付web2.0网站, 特 ...

  4. epel-release的卸载重装

    1.yum remove epel-release 2.清空epel目录:rm -rf /var/cache/yum/x86_64/6/epel/ 3.安装,yum install  epel-rel ...

  5. Docker(一) 简介

    简介 Docker是一款针对程序开发人员和系统管理员来开发.部署.运行应用的一款虚拟化平台.Docker 可以让你像使用集装箱一样快速的组合成应用,并且可以像运输标准集装箱一样,尽可能的屏蔽代码层面的 ...

  6. python学习Day04--列表

    [主要内容] 1.列表的索引: lst=[1,2,3,4,5,6] print(lst[0])      #获取第一个元素 lst[1]='你好'    #改变列表中的值 2.列表的切片: lst=[ ...

  7. openstack启动云主机的流程

    看一下openstack启动云主机的流程图 通过上图分析可以知道: 1. 用户使用Dashboard或者CLI 把认证信息通过REST请求发送给keystone进行认证.2. Keystone校验用户 ...

  8. 如何在国内下载Eclipse及其插件

    北京理工大学 http://mirror.bit.edu.cn/eclipse/ 中国科学技术大学 http://mirrors.ustc.edu.cn/eclipse/ 大连东软信息学院 http: ...

  9. python 内置模块之ConfigParser--配置读写

    用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser. #配置文件test.cfg [section1] k1 = v1 k2 :v2 k3 = 1 ...

  10. Luogu P1280 尼可的任务(dp)

    题意: 时间为n,有k个任务,每个任务有一个开始时间和持续时间,从第一分钟开始,如果有开始的任务就要做,问最大空闲时间 n,k<=1e5 思路: 设 dp[i]为i~n时间中最大空闲时间,vec ...