经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python3 » 查看文章
Python3二分查找库函数bisect(),bisect_left()和bisect_right()的区别
来源:jb51  时间:2023/3/14 8:46:02  对本文有异议

前提:列表有序!!!

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

用法:

  1. index1 = bisect(ls, x) #第1个参数是列表,第2个参数是要查找的数,返回值为索引
  2. index2 = bisect_left(ls, x)
  3. 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。

  1. import bisect
  2. ls = [1,5,9,13,17]
  3. index1 = bisect.bisect(ls,7)
  4. index2 = bisect.bisect_left(ls,7)
  5. index3 = bisect.bisect_right(ls,7)
  6. 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。

  1. import bisect
  2. ls = [1,5,9,13,17]
  3. index1 = bisect.bisect(ls,9)
  4. index2 = bisect.bisect_left(ls,9)
  5. index3 = bisect.bisect_right(ls,9)
  6. 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。

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

程序运行结果为,

index1 = 4, index2 = 1, index3 = 4

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号