a = [1,3,5,7,9]
# 查找第一个大于等于x的位置
def lower_bound(l, r, x):
while l <= r:
mid = (l+r) // 2
if a[mid] < x:
l = mid + 1
else:
r = mid - 1
return l
# 查找第一个大于x的位置
def upper_bound(l, r, x):
while l <= r:
mid = (l+r) // 2
if a[mid] <= x:
l = mid + 1
else:
r = mid - 1
return l
print(lower_bound(0, 4, 5)) # 2
print(upper_bound(0, 4, 5)) # 3
标签:二分,lower,python,bound,while,查找
From: https://www.cnblogs.com/wstong2052/p/17516422.html