bisect_left,bisect_right,bisect的用法,区别以源码分析

2023-12-19 03:36

本文主要是介绍bisect_left,bisect_right,bisect的用法,区别以源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

bisect_left(*args, **kwargs)

向一个数组插入一个数字,返回应该插入的位置。
如果这个数字不存在于这个数组中,则返回第一个比这个数大的数的索引
如果这个数字存在,则返回数组中这个数的位置的最小值(即最左边那个索引)

案例1:这个数在数组中不存在

arr = [1, 3, 3, 5, 6, 6, 7, 9, 11]# 在已排序的列表中查找元素 6 的插入位置
index = bisect_left(arr, 5.5)print(f"Insert 6 at index {index} to maintain sorted order.")

执行结果:

Insert 6 at index 4 to maintain sorted order.

我们找到了第一个大于5.5的数字6的位置,输出4

案例2:这个数在数组中存在

我们修改一下代码,寻找6的位置

from bisect import bisect_left, bisect, bisect_rightarr = [1, 3, 3, 5, 6, 6, 7, 9, 11]# 在已排序的列表中查找元素 6 的插入位置
index = bisect_left(arr, 6)print(f"Insert 6 at index {index} to maintain sorted order.")

执行结果:

Insert 6 at index 4 to maintain sorted order.

我们发现还是4

bisect_right(*args, **kwargs)

向一个数组插入一个数字,返回应该插入的位置。
作用:返回第一个比这个数大的数的索引

案例1:这个数在数组中不存在

from bisect import bisect_left, bisect, bisect_rightarr = [1, 3, 3, 5, 6, 6, 7, 9, 11]# 在已排序的列表中查找元素 6 的插入位置index = bisect_right(arr, 6.5)print(f"Insert 6 at index {index} to maintain sorted order.")

执行结果:

Insert 6 at index 6 to maintain sorted order.

数字7的位置被输出

案例2:这个数在数组中存在

from bisect import bisect_left, bisect, bisect_rightarr = [1, 3, 3, 5, 6, 6, 7, 9, 11]# 在已排序的列表中查找元素 6 的插入位置index = bisect_right(arr, 6)print(f"Insert 6 at index {index} to maintain sorted order.")

执行结果:

Insert 6 at index 6 to maintain sorted order.

数字7的位置被输出

对比bisect_left 和 bisect_right

相同点:
当第二个参数数字x不在第一个参数数组arr中时候,二者都会返回arr中第一个比x大的数的位置

不同点:
当arr中存在x,bisect_left会返回arr中x的最小索引,而bisect_right会返回第一个比x大的数的位置

bisect()

我们查看源码发现:
在这里插入图片描述
bisect就是bisect_right

完整代码

from bisect import bisect_left, bisect, bisect_rightarr = [1, 3, 3, 5, 6, 6, 7, 9, 11]# 在已排序的列表中查找元素 6 的插入位置index = bisect_right(arr, 6)print(f"Insert 6 at index {index} to maintain sorted order.")index = bisect(arr, 6)print(f"Insert 6 at index {index} to maintain sorted order.")index = bisect_left(arr, 6)print(f"Insert 6 at index {index} to maintain sorted order.")

结果:

Insert 6 at index 6 to maintain sorted order.
Insert 6 at index 6 to maintain sorted order.
Insert 6 at index 4 to maintain sorted order.

源码分析

我们先来看 bisect_right 的源码

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 ina[i:] have e > x.  So if x already appears in the list, a.insert(x) willinsert just after the rightmost x already there.Optional args lo (default 0) and hi (default len(a)) bound theslice 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# Use __lt__ to match the logic in list.sort() and in heapqif x < a[mid]: hi = midelse: lo = mid+1return lo

bisect_left 的源码

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 ina[i:] have e >= x.  So if x already appears in the list, a.insert(x) willinsert just before the leftmost x already there.Optional args lo (default 0) and hi (default len(a)) bound theslice 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# Use __lt__ to match the logic in list.sort() and in heapqif a[mid] < x: lo = mid+1else: hi = midreturn lo

我们观察到这两种实现方式主要在于下面两行:
bisect_right:

        if x < a[mid]: hi = midelse: lo = mid+1

bisect_left:

        if a[mid] < x: lo = mid+1else: hi = mid

我们观察到,两段源码都会返回lo,即左边界,所以我们关注一下这两行代码对于左边界的影响:
在bisect_right中,只有当 x=a[mid] or x>a[mid]时,lo才会更新为mid+1,所以最终的lo只可能是第一个大于x的索引
在bisect_left中,当 a[mid] < x时,lo会更新为mid+1,此时我们想要的索引位置必然在mid右侧,所以lo可以为相同的x的第一次出现的位置;同时我们注意到当 a[mid] >= x时,hi=mid,说明当lo取到了相同的数的最左侧时,hi右端点其实会向左平移的,所以lo既可以是数组中第一个大于x的数的索引,也可以是相同的x的最左侧第一个x的索引

这篇关于bisect_left,bisect_right,bisect的用法,区别以源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/510763

相关文章

Vue和React受控组件的区别小结

《Vue和React受控组件的区别小结》本文主要介绍了Vue和React受控组件的区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录背景React 的实现vue3 的实现写法一:直接修改事件参数写法二:通过ref引用 DOMVu

Python中logging模块用法示例总结

《Python中logging模块用法示例总结》在Python中logging模块是一个强大的日志记录工具,它允许用户将程序运行期间产生的日志信息输出到控制台或者写入到文件中,:本文主要介绍Pyt... 目录前言一. 基本使用1. 五种日志等级2.  设置报告等级3. 自定义格式4. C语言风格的格式化方法

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

Java中HashMap的用法详细介绍

《Java中HashMap的用法详细介绍》JavaHashMap是一种高效的数据结构,用于存储键值对,它是基于哈希表实现的,提供快速的插入、删除和查找操作,:本文主要介绍Java中HashMap... 目录一.HashMap1.基本概念2.底层数据结构:3.HashCode和equals方法为什么重写Has

Android协程高级用法大全

《Android协程高级用法大全》这篇文章给大家介绍Android协程高级用法大全,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友跟随小编一起学习吧... 目录1️⃣ 协程作用域(CoroutineScope)与生命周期绑定Activity/Fragment 中手

Go之errors.New和fmt.Errorf 的区别小结

《Go之errors.New和fmt.Errorf的区别小结》本文主要介绍了Go之errors.New和fmt.Errorf的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考... 目录error的基本用法1. 获取错误信息2. 在条件判断中使用基本区别1.函数签名2.使用场景详细对

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

Redis中哨兵机制和集群的区别及说明

《Redis中哨兵机制和集群的区别及说明》Redis哨兵通过主从复制实现高可用,适用于中小规模数据;集群采用分布式分片,支持动态扩展,适合大规模数据,哨兵管理简单但扩展性弱,集群性能更强但架构复杂,根... 目录一、架构设计与节点角色1. 哨兵机制(Sentinel)2. 集群(Cluster)二、数据分片

Python中yield的用法和实际应用示例

《Python中yield的用法和实际应用示例》在Python中,yield关键字主要用于生成器函数(generatorfunctions)中,其目的是使函数能够像迭代器一样工作,即可以被遍历,但不会... 目录python中yield的用法详解一、引言二、yield的基本用法1、yield与生成器2、yi

深度解析Python yfinance的核心功能和高级用法

《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?