iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python3二分查找库函数bisect(),bisect_left()和bisect_right()的区别
  • 699
分享到

Python3二分查找库函数bisect(),bisect_left()和bisect_right()的区别

Python3二分查找库函数bisect()bisect_left()和bisec_right()区别 2023-03-11 17:03:50 699人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录case 1case 2case 3前提:列表有序!!! bisect()和bisect_right()等同,那下面就介绍bisect_left()和bise

前提:列表有序!!!

bisect()和bisect_right()等同,那下面就介绍bisect_left()和bisec_right()的区别!

用法:

index1 = bisect(ls, x)   #第1个参数是列表,第2个参数是要查找的数,返回值为索引
index2 = bisect_left(ls, x)
index3 = bisec_right(ls, x)

bisect.bisect和bisect.bisect_right返回大于x的第一个下标(相当于c++中的upper_bound),bisect.bisect_left返回大于等于x的第一个下标(相当于C++中的lower_bound)。

case 1

如果列表中没有元素x,那么bisect_left(ls, x)和bisec_right(ls, x)返回相同的值,该值是x在ls中“合适的插入点索引,使得数组有序”。此时,ls[index2] > x,ls[index3] > x。

import bisect
ls = [1,5,9,13,17]
index1 = bisect.bisect(ls,7)
index2 = bisect.bisect_left(ls,7)
index3 = bisect.bisect_right(ls,7)
print("index1 = {}, index2 = {}, index3 = {}".fORMat(index1, index2, index3))

程序运行结果为,

index1 = 2, index2 = 2, index3 = 2

case 2

如果列表中只有一个元素等于x,那么bisect_left(ls, x)的值是x在ls中的索引,ls[index2] = x。而bisec_right(ls, x)的值是x在ls中的索引加1,ls[index3] > x。

import bisect
ls = [1,5,9,13,17]
index1 = bisect.bisect(ls,9)
index2 = bisect.bisect_left(ls,9)
index3 = bisect.bisect_right(ls,9)
print("index1 = {}, index2 = {}, index3 = {}".format(index1, index2, index3))

程序运行结果为,

index1 = 3, index2 = 2, index3 = 3

case 3

如果列表中存在多个元素等于x,那么bisect_left(ls, x)返回最左边的那个索引,此时ls[index2] = x。bisect_right(ls, x)返回最右边的那个索引加1,此时ls[index3] > x。

import bisect
ls = [1,5,5,5,17]
index1 = bisect.bisect(ls,5)
index2 = bisect.bisect_left(ls,5)
index3 = bisect.bisect_right(ls,5)
print("index1 = {}, index2 = {}, index3 = {}".format(index1, index2, index3))

程序运行结果为,

index1 = 4, index2 = 1, index3 = 4

到此这篇关于python3二分查找库函数bisect(), bisect_left()和bisect_right()介绍的文章就介绍到这了,更多相关python3二分查找库函数bisect()内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python3二分查找库函数bisect(),bisect_left()和bisect_right()的区别

本文链接: https://www.lsjlt.com/news/199374.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作