Created
September 18, 2019 14:39
-
-
Save sehajyang/a3bc99fbae97f1d3684a293547fc0bf6 to your computer and use it in GitHub Desktop.
feat.thanos search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import * | |
import pytest | |
def solution(arr: list, target: int) -> int: | |
start_idx = 0 | |
end_idx = len(arr) | |
while 1: | |
mid_idx = (start_idx + end_idx) // 2 | |
mid_value = arr[mid_idx] | |
# 앞 뒤 인덱스 더하고 가운데 인덱스의 값 리턴 | |
if mid_value > target: | |
end_idx = mid_idx | |
elif end_idx - start_idx == 1: | |
if mid_value == target: | |
return mid_idx | |
else: | |
return -1 | |
else: | |
start_idx = mid_idx | |
def test_solution(): | |
arr = [1, 3, 5, 8, 17, 60, 70] | |
arr2 = [2, 4] | |
assert solution(arr, 60) == 5 | |
assert solution(arr, 1) == 0 | |
assert solution(arr, 8) == 3 | |
assert solution(arr, 17) == 4 | |
assert solution(arr, 70) == 6 | |
assert solution(arr2, 4) == 1 | |
assert solution(arr2, 2) == 0 | |
assert solution(arr2, 100) == -1 | |
if __name__ == '__main__': | |
pytest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment