bisect_left(nums,target),bisect_right(nums,target)是python内置的函数,可以便捷的帮我们完成一些有序序列的查找工作,现在将用三个样例进行讲解演示
前提注意事项:
导入函数模块
待处理序列必须有序!!!
from bisect import bisect_left,bisect_right
nums=[1,23,5,4,6,547,4,4,7,81,2]
# 注意使用前必须是有序数组
nums.sort()
这里以列表nums=[1,23,5,4,6,547,4,4,7,81,2] 为例
case 1 target=3 不在nums中 目标数不在数组中,bisect_left()和bisect_right()返回相同的结果, 该结果是target在nums中 “合适的插入点索引,使得数组有序”。 此时,nums[res1] > x,nums[res2] > x。
target=3
res1=bisect_left(nums,target)
res2=bisect_right(nums,target)
print(f"排序后数组为:{nums}")
print(f"待查找数字为:{target}")
print(f"bisect_left={res1};bisect_right={res2}")
结果:
排序后数组为:[1, 2, 4, 4, 4, 5, 6, 7, 23, 81, 547]
待查找数字为:3
bisect_left=2;bisect_right=2
case 2 target=7 在nums中仅存在一个 数组中只有一个待查找数字 bisect_left的值是target在nums中的索引, nums[res1] = target。 bisect_right的值是target在nums中的索引加1, nums[res2] > target。
target=7
res1=bisect_left(nums,target)
res2=bisect_right(nums,target)
print(f"排序后数组为:{nums}")
print(f"待查找数字为:{target}")
print(f"bisect_left={res1};bisect_right={res2}")
结果:
排序后数组为:[1, 2, 4, 4, 4, 5, 6, 7, 23, 81, 547]
待查找数字为:7
bisect_left=7;bisect_right=8
case 3 targe=4 在nums中多次出现 如果列表中存在多个元素等于target, bisect_left()返回最左边(第一次出现位置)的那个索引, nums[res1] = target。 bisect_right()返回最右边(最后一次出现位置)的那个索引加1, nums[res2] > target。
target=4
res1=bisect_left(nums,target)
res2=bisect_right(nums,target)
print(f"排序后数组为:{nums}")
print(f"待查找数字为:{target}")
print(f"bisect_left={res1};bisect_right={res2}")
结果:
排序后数组为:[1, 2, 4, 4, 4, 5, 6, 7, 23, 81, 547]
待查找数字为:4
bisect_left=2;bisect_right=5