[python]원소 개수 찾기 - bisect vs Counter

iamjinseo·2022년 10월 18일
0

스터디

목록 보기
4/8

이코테 이진 탐색 알고리즘 파트를 보던 중, 파이썬 이진 탐색 라이브러리로 '값이 특정 범위에 속하는 데이터 개수 구하기'를 구현할 수 있다는 걸 알아냈다.

bisect vs Counter

그렇다면 리스트 내에서 원소 개수를 찾을 때, bisectCounter중 어떤 라이브러리로 구현할 때 빠르게 동작할까?

# bisect로 원소개수찾기 vs Counter로 원소개수찾기
from bisect import bisect_left, bisect_right
from collections import Counter
from copy import copy
import time
from random import randint

# 값이 [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 =[]
for i in range(20000):
    a.append(randint(1, 100))
b = copy(a)

start_bisect = time.time()
a.sort()
print("bisect로 찾은4 개수:", count_by_range(a, 4, 4))
end_bisect = time.time()
print("bisect : ", end_bisect-start_bisect)

start_count = time.time()
b_counter = Counter(b)
print("Counter로 찾은4 개수:", b_counter[4])
end_count = time.time()
print("count : ", end_count-start_count)

# 종합평가 : Counter가 더 빠름

결론

정답은 Counter다.

bisect가 더 느리지만 특정 범위에 속하는 값의 개수를 찾을 때도 사용할 수 있으니, 알아두는 편이 좋다.

profile
일단 뭐라도 해보는 중

0개의 댓글