当前位置:网站首页>Bisect -- insert new data into the list and keep it in order
Bisect -- insert new data into the list and keep it in order
2022-04-22 16:58:00 【lilibiu】
Insertion method based on dichotomy
Official website
bisect—— Website to explain
This module provides support for ordered lists , So that they can still be in order when inserting new data . For long lists , If the comparison operation of its containing elements is very expensive , This can be an improvement on the more common approach .
This module is called bisect Because of its Used the basic dichotomy (bisection) Algorithm . The source code can also be used as a great algorithm example ( The boundary judgment is also done !)
Four ways
bisect.bisect_left(a, x, lo=0, hi=len(a))
stay a Find x Appropriate insertion points to maintain order . Parameters lo and hi It can be used to identify subsets that need to be considered ; By default, the entire list is used . If x Already in a In existence , Then the insertion point will be before the existing element ( On the left ). If a Is a list of (list) Words , The return value can be placed in list.insert() The first parameter of .
The insertion point returned i You can put arrays a In two parts .
On the left is all(val < x for val in a[lo:i]) ,
The right side is all(val >= x for val in a[i:hi]) .
bisect.bisect_right(a, x, lo=0, hi=len(a))
Be similar to bisect_left(), The insertion point returned is a Element already exists in x The right side of the .
The insertion point returned i You can put arrays a In two parts .
On the left is all(val <= x for val in a[lo:i]),
The right side is all(val > x for val in a[i:hi])
Pay attention to and left The difference between the equal sign of
bisect.insort_left(a, x, lo=0, hi=len(a))
take x Insert into an ordered sequence a in , And keep it in order . If a Orderly words , This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x). Note that the search is O(log n) Of , The insertion is O(n) Of .
bisect.insort_right(a, x, lo=0, hi=len(a))
Be similar to insort_left(), But put x Insert into a Element already exists in x The right side of the .
Realization principle
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect_left(a, x)
if i:
return a[i-1]
raise ValueError
def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect_right(a, x)
if i:
return a[i-1]
raise ValueError
def find_gt(a, x):
'Find leftmost value greater than x'
i = bisect_right(a, x)
if i != len(a):
return a[i]
raise ValueError
def find_ge(a, x):
'Find leftmost item greater than or equal to x'
i = bisect_left(a, x)
if i != len(a):
return a[i]
raise ValueError
There are more cow usages !
bisect Directly realize the ranking of grades :
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect(breakpoints, score)
return grades[i]
[grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
And sorted() Functions are different , about bisect() In terms of functions ,key perhaps reversed Parameters don't make any sense . Because this will lead to inefficient design ( Continuous call bisect Function time , Will not “ remember ” Of keys searched in the past ).
On the contrary , It's best to search a pre calculated list of keys , To find the index of relevant records .
data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
data.sort(key=lambda r: r[1])
keys = [r[1] for r in data] # precomputed list of keys
data[bisect_left(keys, 0)]
data[bisect_left(keys, 1)]
data[bisect_left(keys, 5)]
data[bisect_left(keys, 8)]
application :
about leetcode 1385. The distance between two arrays
Here are two arrays of integers arr1 , arr2 And an integer d , Please return the... Between two arrays Distance value .
「 Distance value 」 Number of elements defined as meeting this distance requirement : For elements arr1[i] , There are no elements arr2[j] Satisfy
|arr1[i]-arr2[j]| <= d .
Key:
hold arr2 After the sorting , For each of these arr1 The elements in , All in arr2 in Find the corresponding nearest value , If these two adjacent values meet the distance d, Then the rest of the values are satisfied .
We need to pay attention to , There are two adjacent cases , Left and right , And at the same time meet .
The code is as follows :
class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
arr2.sort()
ans = 0
for x in arr1:
p = bisect.bisect_left(arr2,x)
if p ==len(arr2) or abs(x - arr2[p])>d:
if p == 0 or abs(x - arr2[p-1])>d:
ans +=1
return ans
First time to know bisect, Amazing !
版权声明
本文为[lilibiu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221652550618.html
边栏推荐
- Vscode most complete practical plug-in (VIP collection version)
- RT thread studio workspace encoding is set to UTF-8
- 运维自动化之ansible--(playbook模式)
- numpy基础大全(创建、索引、常用函数)
- 刘畊宏是抖音的钻头
- What are the functional problems of UI testing- Ze zhongyun test
- [Unity] 战斗系统学习 12:Switchable
- [filtering and convolution (III)]
- Detailed data of db107-asemi rectifier bridge
- 【角点检测】
猜你喜欢

Dispute over stock: Gome retail explores the way to break the situation with full retail

AQS源码阅读
![[Ansys Workbench] Mechanical 界面显示模型树窗口和详细信息窗口](/img/75/d6da5800cf3d1952d1c052a189608a.png)
[Ansys Workbench] Mechanical 界面显示模型树窗口和详细信息窗口
![[filtering and convolution (III)]](/img/46/57b5e1490d1fda10c95fc8bc66a2b2.png)
[filtering and convolution (III)]

红杉中国带队,投了两位女创始人

SaaS 长河下,AfterShip 技术升级的“加减法”

Explain JVM memory model in detail
![[unity] make aim IK 1 with animation rig](/img/52/b8ee9d0982a8671356954fbbad775d.png)
[unity] make aim IK 1 with animation rig

认知系列4: 《认知突围》笔记

VSCode插件打包迁移与指定位置
随机推荐
[Dahua cloud native] wonderful relationship between message queue and express cabinet (with video)
[Unity] 战斗系统学习 12:Switchable
leetcode:451. Sort by character frequency
【ES6】扩展运算符、symbol、迭代器
20220421 hardware imaging
【滤波与卷积(三)】
Idea code refactoring tips (VIP collection version)
国产手机品牌才发现,没有国内消费者支持它们什么也不是
AQS source code reading
记录一次关于redis取值总不是想要的生产小意外
RT thread studio workspace encoding is set to UTF-8
IDEA代码重构小技巧(VIP典藏版)
云原生大厦的基石之一「云原生可观测性」
认知系列4: 《认知突围》笔记
运维自动化之ansible--(playbook模式)
7 capabilities of data analysis: sorting out data needs
20220420 reasoning framework analyzes what is gradient
bisect——对列表插入新数据仍然保持有序
Blue Bridge Cup practice 014
[unity] make aim IK 1 with animation rig