Python
[파이썬] bisect
bbomi
2021. 7. 2. 00:04
https://docs.python.org/ko/3.9/library/bisect.html
정렬된 list를 관리해줄 때 유용한 모듈입니다 (이진탐색).
예시1: 정렬된 list에서 해당 숫자가 어디에 위치하는지 찾을 때
import bisect
mylist = [1, 2, 3, 7, 9, 11, 33]
print(bisect.bisect(mylist, 7))
'''
4
'''
7이 4번째 위치하기 때문에 4 출력해줍니다.
예시2: 정렬된 list에서 숫자를 새로 넣을 때
insort
mylist = [1, 3, 4, 5]
bisect.insort(mylist , 2)
print(mylist)
'''
[1, 2, 3, 4, 5]
'''
2가 본인 자리를 찾아서 (1과 3 사이) 들어갑니다.
예시3: bisect_left/bisect_right, insort_left/insort_right
bisect_left: list에서 x가 찾아 들어갈 위치를 구함. 같은 값이 list에 존재할 경우 해당 값의 왼쪽 위치 반환
mylist = [1, 2, 3, 4, 5]
print(bisect.bisect_left(mylist, 4))
'''
3
'''
bisect_right: bisect_left와 같지만 같은 값이 list에 존재할 경우 해당 값의 오른쪽 위치 반환
mylist = [1, 2, 3, 4, 5]
print(bisect.bisect_right(mylist, 4))
'''
4
'''
insort_left / insort_right: bisect_left / bisect_right의 위치에 x값을 넣어줍니다.
mylist = [1, 2, 3, 4, 5]
bisect.insort_left(mylist, 4)
mylist
'''
[1, 2, 3, 4, 4, 5]
'''
예시4: A~F 학점을 점수 별로 만든다고 했을 때
import bisect
def grade(score):
breakpoints = (50, 60, 70, 90, 100)
g = 'FDCBA'
return g[bisect.bisect_right(breakpoints, score)]
print(grade(90))
'''
A
'''
~49: F
50~59: D
60~69: C
70~89: B
90~100: A
101~ : 초과 (list index out of range 에러)
위의 함수에서 grade(90) 이면 A가 출력됩니다.