[python] bisect๋ชจ๋“ˆ

Minhee kangยท2021๋…„ 7์›” 2์ผ
2

Python

๋ชฉ๋ก ๋ณด๊ธฐ
6/25
# bisect์€ ์ด์ง„ ๊ฒ€์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ง€์›
# ์ด์ง„ ๊ฒ€์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ๊น”๋”ํ•˜๊ฒŒ ๋ชจ๋“ˆ ํ˜•ํƒœ๋กœ ๊ตฌํ˜„๋˜์–ด ์žˆ์Œ
# ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ a ์— ๋ฐ์ดํ„ฐ x์„ ์‚ฝ์ž…ํ•œ๋‹ค ๊ฐ€์ •
# bisect_left(a, x) 
# -> ์ •๋ ฌ ๋œ ์ˆœ์„œ๋ฅผ ์œ ์ง€ํ•˜๋ฉฐ a์— x๋ฅผ ์‚ฝ์ž…ํ•  ๋•Œ, ๊ฐ€์žฅ ์™ผ์ชฝ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜
# bisect_right(a, x)
# -> ์ •๋ ฌ ๋œ ์ˆœ์„œ๋ฅผ ์œ ์ง€ํ•˜๋ฉฐ a์— x๋ฅผ ์‚ฝ์ž…ํ•  ๋•Œ, ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜

import bisect

nums = [1,2,3,3,3,5,6,8,9]
nums.sort() #binary search๋Š” ์ •๋ ฌ ๋œ ๋ฐฐ์—ด์—์„œ ์‚ฌ์šฉํ•ด์•ผํ•จ

print(bisect.bisect_left(nums, 10)) # 9
print(bisect.bisect_right(nums, 10)) # 9

print(bisect.bisect_left(nums, 3))   # 2
print(bisect.bisect_right(nums, 3))  # 5

๐Ÿ“• ์ถ”๊ฐ€

ํŒŒ์ด์ฌ bisect๋ชจ๋“ˆ์˜ ๊ณต์‹ ๋ฌธ์„œ

#bisect.bisect_left(a, x, lo=0, hi=len(a))
#๋งค๊ฐœ ๋ณ€์ˆ˜ lo ์™€ hi๋Š” ๊ณ ๋ คํ•ด์•ผ ํ•  ๋ฆฌ์ŠคํŠธ์˜ ๋ถ€๋ถ„์ง‘ํ•ฉ์„ ์ง€์ •ํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ
#bisect.bisect_left(๋ฐฐ์—ด, ํƒ€๊ฒŸ๋„˜๋ฒ„, ์‹œ์ž‘์ธ๋ฑ์Šค, ๋งˆ์ง€๋ง‰์ธ๋ฑ์Šค + 1) ๋ผ๊ณ  ์ดํ•ด!

import bisect

nums = [-1, 0, 1, 2, 3, 4, 4, 9, 56, 90]
print(bisect.bisect_left(nums, 4))  #5์ถœ๋ ฅ
print(bisect.bisect_left(nums,4, 6))  #4์ถœ๋ ฅ

0๊ฐœ์˜ ๋Œ“๊ธ€