[Python] bisect_left/right

Hyuntae Jung·2022년 9월 1일
0

Algorithm

목록 보기
13/17
post-thumbnail

1. 이분탐색

from bisect import bisect_left, bisect_right

v = (0, 1, 3, 3, 6, 6, 6, 7, 8, 8, 9)
three = bisect_right(v, 3) - bisect_left(v, 3) # 4 - 2
four = bisect_right(v, 4) - bisect_left(v, 4) # 4 - 4
six = bisect_right(v, 6) - bisect_left(v, 6) # 7 - 4
print(f'number of 3: {three}') # 2
print(f'number of 4: {four}') # 0
print(f'number of 6: {six}') # 3

bisect_right(v, m) 은 m보다 큰값의 가장 낮은 인덱스를 추출한다.
bisect_left(v, m) 은 m이상의 가장 낮은 인덱스를 추출한다.

C++에서의 upper_bound, lower_bound와 동일하게 작동한다.

0개의 댓글