python排序序列的二进制搜索
binary-search的Python项目详细描述
python中的二进制搜索
对已排序序列(列表、元组)进行二进制搜索,以获取第一个元素>=
或>
一个值(类似于C++的^ {< CD3> }和^ {< CD4}})。
对于typing
模块需要python>;=3.5,对于enum
模块需要>;=3.4,但是您可以很容易地
从binary_search/__init__.py
中提取search
函数(如果需要较低版本)。
安装
pip install binary-search
用法
有关更多示例用法,请参见tests.py
。
importbinary_searchasbssorted_sequence=(2,5,7,9)a=bs.search(sorted_sequence,5)print(a)# 1 - the index of the first element >= 5b=bs.search(sorted_sequence,6)print(b)# 2 - the index of the first element >= 6 (element 2 with value 7)
您还可以使用与sorted
importbinary_searchasbsimportrandom# sequence of 10 random pairs of integerssequence=[(random.randint(),random.randint())for_inrange(10)]# sort and search just using the first integerkey=lambdapair:pair[0]sorted_sequence=sorted(sequence,key=key)bs.search(sorted_sequence,[5,None],key=key)
开发和测试
- 分叉存储库
- 克隆您的叉子
- 以可编辑模式安装
pip install -e .
- 进行任何更改并将新测试添加到
tests.py
- 运行pytest
python -m pytest
- 承诺并推到叉子上
- 发出拉取请求(将分叉合并回主回购)