《流畅的Python》
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/1/19 9:59
# @Author : Lili
# @File : exp5.py
# @Description : 用bisect来管理已排序的序列
# 包含bisect和insort两个主要函数,均利用二分查找算法
import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
for needle in reversed(NEEDLES):
position = bisect_fn(HAYSTACK, needle)
offset = position * ' |'
print(ROW_FMT.format(needle, position, offset))
if __name__ == '__main__':
if sys.argv[-1] == 'left':
bisect_fn = bisect.bisect_left
else:
bisect_fn = bisect.bisect
print('DEMO:', bisect_fn.__name__)
print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
demo(bisect_fn)
# left 与 right:针对那些值相等但是形式不同的数据类型
# bisect可以用来建立一个用数字作为索引的查询表格,比如把分数和成绩对应起来
# 示例里的代码来自 bisect 模块的文档(https://docs.python.org/3/library/bisect.html)。
# 文档里列举了一些利用 bisect 的函数,它们可以在很长的有序序列中作为 index 的替代,用来更快地查找一个元素的位置。
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect.bisect(breakpoints, score)
return grades[i]
print([grade(score) for score in [33, 99, 77, 70, 89, 90, 100]])
# 用bisect.insort插入元素
import random
SIZE = 7
random.seed(1729)
my_list = []
for i in range(SIZE):
new_item = random.randrange(SIZE*2)
bisect.insort(my_list, new_item)
print('%2d ->' % new_item, my_list)
# insort和bisect一样,有lo和hi两个可选参数来控制查找的范围,都有变体insort_left,bisect_left