이 함수는 deprecated 되었습니다. bisect_모듈을_이용한_파라메트릭_서치_구현을 참고해서 구현하세요
# N binary_search
# I {"version": "1.0", "typing": ["Callable"]}
def binary_search(beg: int, end: int, predicate: Callable[[int], bool]) -> int:
"""Returns the minimum int X in [beg, end) where predicate(X) is true."""
if not predicate(end - 1):
raise ValueError
while beg < end:
mid = (beg + end) // 2
if predicate(mid):
end = mid
else:
beg = mid + 1
return beg
T = TypeVar('T')
# N nth_element
# I {"version": "1.0", "typing": ["Sequence, TypeVar"], "const": ["T"]}
def nth_element(arr: Sequence[T], n: int, threshold: int = 500_000) -> T:
"""Returns n-th smallest element from given sequence."""
def nth_element_rec(arr, n):
if len(arr) <= threshold:
return sorted(arr)[n - 1]
pivot = sorted([arr[0], arr[-1], arr[len(arr) // 2]])[1]
sub = [el for el in arr if el < pivot]
if n <= len(sub):
return nth_element_rec(sub, n)
sub = [el for el in arr if el > pivot]
if (l := n - (len(arr) - len(sub))) > 0:
return nth_element_rec(sub, l)
return pivot
if not 1 <= n <= len(arr):
raise ValueError(f'n({n}) must be in [1, {len(arr)}]')
return nth_element_rec(arr, n)