< bisect >
- 이진탐색을 쉽게 구현할 수 있기 위한 라이브러리
- 정렬된 배열에서 특정한 원소를 찾아야할 때 매우 효과적
- bisect_left()와 bisect_right() 함수가 가장 중요하게 사용됨
- 시간복잡도 O(logN)
# 정렬된 리스트에 새로운 데이터를 삽입하는 예시
from bisect import bisect_left, bisect_right
a = [1, 2, 4, 4, 8]
x = 4
print('bisect_left index :', bisect_left(a,x))
print('bisect_right index :', bisect_right(a,x))
from bisect import bisect_left, bisect_right
# 값이 [left_value, right_value]인 데이터 개수를 반환하는 함수
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]
# 값이 4인 데이터 개수 출력
print(count_by_range(a, 4, 4))
# 값이 [-1, 3] 범위에 있는 데이터 개수 출력
print(count_by_range(a, -1, 3))