[Python] bisect - 이진 탐색
잘못된 부분이 있다면 댓글부탁드립니다:D
- 아래에서 ‘배열’은 ‘리스트’ 또는 ‘튜플’입니다.
bisect_left - 왼쪽 위치 찾기
bisect_left(배열, 찾을 숫자)
from bisect import bisect_left
arr = [0, 2, 4, 6, 8]
result = bisect_left(arr, 0)
print(result) #결과: 0
result = bisect_left(arr, 3)
print(result) #결과: 2
result = bisect_left(arr, 4)
print(result) #결과: 2
bisect_right (=bisect) - 오른쪽 위치 찾기
bisect_right(배열, 찾을 숫자)
from bisect import bisect_right
arr = [0, 2, 4, 6, 8]
result = bisect_right(arr, 0)
print(result) #결과: 1
result = bisect_right(arr, 3)
print(result) #결과 2
result = bisect_right(arr, 4)
print(result) #결과 3
bisect(배열, 찾을 숫자)
from bisect import bisect
arr = [0, 2, 4, 6, 8]
result = bisect(arr, 0)
print(result) #결과: 1
result = bisect(arr, 3)
print(result) #결과: 2
result = bisect(arr, 4)
print(result) #결과: 3
insort_left - 왼쪽에 삽입
insort_left(배열, 찾을숫자)
from bisect import insort_left
arr = [0, 2, 4, 6, 8]
insort_left(arr, 0)
print(arr) #결과: [0, 0, 2, 4, 6, 8]
insort_left(arr, 3)
print(arr) #결과: [0, 0, 2, 3, 4, 6, 8]
insort_left(arr, 4)
print(arr) #결과: [0, 0, 2, 3, 4, 4, 6, 8]
insort_right (=insort) - 오른쪽에 삽입
insort_right(배열, 찾을숫자)
from bisect import insort_right
arr = [0, 2, 4, 6, 8]
insort_right(arr, 0)
print(arr) #결과: [0, 0, 2, 4, 6, 8]
insort_right(arr, 3)
print(arr) #결과: [0, 0, 2, 3, 4, 6, 8]
insort_right(arr, 4)
print(arr) #결과: [0, 0, 2, 3, 4, 4, 6, 8]
insort(배열, 찾을숫자)
from bisect import insort
arr = [0, 2, 4, 6, 8]
insort(arr, 0)
print(arr) #결과: [0, 0, 2, 4, 6, 8]
insort(arr, 3)
print(arr) #결과: [0, 0, 2, 3, 4, 6, 8]
insort(arr, 4)
print(arr) #결과: [0, 0, 2, 3, 4, 4, 6, 8]
댓글남기기