from bisect import bisect_left, bisect_right
arr = [1, 2, 4, 4, 8]
x = 4
print(bisect_left(arr, x)) // 2
print(bisect_right(arr, x)) // 4
배열에서 해당 숫자가 들어갈 왼쪽 위치와 오른 쪽 위치를 알 수 있다.
이것을 이용해 특정 범위에 속하는 데이터 개수를 구할 수 있다.
from bisect import bisect_left, bisect_right
def count_by_range(a, left_value, right_value):
right_index = bisect_right(a, right_value)
left_index = bisect_left(a, left_value)
return (right_index - left_index)
a = [1, 2, 3, 3, 3, 3, 4, 4, 8, 9]
print(count_by_range(a, 4, 4)) # 2
print(count_by_range(a, -1, 3)) # 6